﻿using System;
using System.IO;
using System.Data;
using System.Text;
using System.Configuration;
using System.Collections.Generic;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Resources;

using CE.Mail;
using CE.User;
using CE.Global;
using CE.Security;
using CE.InputOut;
using CE.Database;
using CE.CarInsurance;
using CXDecryption;

public partial class carinsurance_offline_NonGGPackageApplication : System.Web.UI.Page
{
    private DateTime dateTimeNow = CE.Global.General.GetUTCDateTime();

    protected override void InitializeCulture()
    {
        String selectedCulture = CE.Global.General.SetCulture();
        base.InitializeCulture();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session[CE.Global.General.UserId] == null)
        {
            Response.Redirect("~/SiteUserSecureLogin.aspx");
        }
        if (!IsPostBack)
        {
            lblFinanceUserAlert.Text = "";
            ddlApplicationType.Items.Clear();
            ddlApplicationType.Items.Add(new ListItem(Resources.Proposal.AppTypeNew, "NEW"));
            ddlApplicationType.Items.Add(new ListItem(Resources.Proposal.AppTypeChangeBroker, "CHB"));
            lblNonGGStatus.Text = "0";
            lblPayError.Text = "";
            lblOnlinePayError.Text = "";
            divCar.Visible = false;
            lblSearchMessage.Text = "";
            pnlCarDetails.Visible = false;
            txtCarId.Text = "";
            txtLastQuoteRefNo.Text = "";
            txtLastStep.Text = "";
            LoadOption();
            LoadGarageType();
            LoadInsuranceType();
            LoadVehicleType();
            LoadOccupation();
            LoadDOB();
            LoadCommanceDate();
           
            LoadFileUploadType();
            EnableOnOff(false);
            btnPaySubmit.Enabled = true;
            btnPayNew.Enabled = true;
            trInsurerEmail.Visible = false;
            rfvInsurerEmail.Enabled = false;
            revInsurerEmail.Enabled = false;
           
            chkApprove.Enabled = false;
            chkRefund.Enabled = false;
          
            lblLoadMessage.Text = string.Empty;
            string _IsEdit = CE.Configuration.MyConfigurationManager.GetAppSettingValue("IsNonGGEdit");
            if (_IsEdit == "1")
            {
                EnableOnOff(true);
            }
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "ShowHideDiv('divUpload',false);", true);
            ddlApplicationType_SelectedIndexChanged(null, null);
            if (Request.QueryString["refno"] != null)
            {
                txtSearch.Text = Request.QueryString["refno"].ToString();
                btnSearch_Click(sender, e);

                // 17/07/2013
                GetCallType();
            }
        }
        else
        {
            lblNewCallMessage.Text = "";

            if (!chkSameAddress.Checked)
            {
                trSameAddress1.Style.Add("display", "");
                trSameAddress2.Style.Add("display", "");
                trSameAddress3.Style.Add("display", "");
                refSameAddrName.Enabled = true;
                refSameAddress.Enabled = true;
                refSameAddrSubDistrict.Enabled = true;
                refSameAddrStateProvince.Enabled = true;
                refSameAddrProvince.Enabled = true;
                refSameAddrPostalCode.Enabled = true;
            }
            else
            {
                trSameAddress1.Style.Add("display", "none");
                trSameAddress2.Style.Add("display", "none");
                trSameAddress3.Style.Add("display", "none");
                refSameAddrName.Enabled = false;
                refSameAddress.Enabled = false;
                refSameAddrSubDistrict.Enabled = false;
                refSameAddrStateProvince.Enabled = false;
                refSameAddrProvince.Enabled = false;
                refSameAddrPostalCode.Enabled = false;
            }

            if (ddlOption.Text == "EDIT")
            {
                if (chkExtComDate.Checked)
                {
                    ddlExtComDay.Style.Add("visibility", "visible");
                    ddlExtComMonth.Style.Add("visibility", "visible");
                    ddlExtComYear.Style.Add("visibility", "visible");
                }
                else
                {
                    ddlExtComDay.Style.Add("visibility", "hidden");
                    ddlExtComMonth.Style.Add("visibility", "hidden");
                    ddlExtComYear.Style.Add("visibility", "hidden");
                }
            }
        }
    }

    private void GetCallType()
    {
        try
        {
            if (Request.QueryString["calltype"] != null)
            {
                hidCallType.Value = Request.QueryString["calltype"].ToString();
            }

            if (txtCarId.Text.Trim() != "" && hidCallType.Value == "")
            {
                MyDatabase _db = new MyDatabase();
                string _strSQL = "SELECT TOP 1 CallType from tblCXCRMAgentLeads Where CarId = " + txtCarId.Text + " ORDER BY ModifiedDate DESC ";
                object rtnCallType = _db.ExecuteScalarSqlStatement(_strSQL);
                if (rtnCallType != null)
                {
                    hidCallType.Value = rtnCallType.ToString();
                }
            }
        }
        catch (Exception)
        {
        }
    }

    private DataTable CheckCarId(string strCarId)
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dt = new DataTable();
        string strSql = "SELECT cd.CarId, cd.RefCEUserId, cp.Info8, cp.Info19  FROM tblCarDetailTH cd INNER JOIN tblCarPolicy cp " +
                            "ON cd.RefCEUserID = cp.RefCEUserID And cd.CarID = cp.CECarID " +
                            "WHERE cd.[Status] = 1 AND CarId = " + strCarId;
        _dt = _db.GetDataTable(strSql);
        _db = null;
        return _dt;

    }

    private string GetLastYearRefNo(string strCarID, string strCustomerID)
    {
        MyDatabase _db = new MyDatabase();
        string strSql = "SELECT Info7 FROM tblCarPolicy WHERE Info7 IS NOT NULL AND LEN(Info7) > 0 AND CECarId = " + strCarID + " And RefCEUserID = " + strCustomerID;
        string _lastYearRefNo = string.Empty;
        object _objLastYearRefNo = _db.ExecuteScalarSqlStatement(strSql);

        if (_objLastYearRefNo != null)
        {
            _lastYearRefNo = _objLastYearRefNo.ToString();
        }

        _db = null;
        _objLastYearRefNo = null;

        return _lastYearRefNo;
    }

    private string GetLastYearPolicyNo(string strCarId, string strCustomerId)
    {
        MyDatabase _db = new MyDatabase();
        string strSql = "SELECT Remarks FROM tblNonGGTransaction ";
        strSql += " WHERE TransactionTypeId = 300 AND CECarId = " + strCarId + " AND RefCEUserId = " + strCustomerId;
        string _lastYearPolicyNo = string.Empty;
        object _objLastYearPolicyNo = _db.ExecuteScalarSqlStatement(strSql);

        if (_objLastYearPolicyNo != null)
        {
            _lastYearPolicyNo = _objLastYearPolicyNo.ToString();
        }

        _db = null;
        _objLastYearPolicyNo = null;

        return _lastYearPolicyNo;
    }

    protected void btnAppSummary_Click(object sender, EventArgs e)
    {
        Response.Redirect("ApplicationStatus.aspx?search=" + lblUpRefNo.Text);
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        txtAgentRemarkDetails.Text = "";
        btnPaymentApproval.Enabled = false;
        divPayList.Visible = false;
        grvPayment.DataSource = null;
        grvPayment.DataBind();
        lblNonGGStatus.Text = "0";
        pnlOptionMessage.Visible = false;
        lblOptionError.Text = string.Empty;
        lblOptionMessage.Text = string.Empty;
        pnlDetails.Visible = false;
        pnlPayment.Visible = false;
        pnlCarDetails.Visible = false;
        pnlApplicationCancel.Visible = false;
        pnlApplicationRetrieve.Visible = false;
        pnlUploadFileList.Visible = false;
        LoadOption();
        if (Server.HtmlEncode(txtSearch.Text).Trim() != "" && Server.HtmlEncode(txtSearch.Text).Trim().Length > 4)
        {
            txtGG.Text = "PROVIDER";
            if (txtSearch.Text.Trim().Substring(0, 2) == "GG")
            {
                txtGG.Text = "GGSPECIAL";
            }
            if (CheckSelectedItem(Server.HtmlEncode(txtSearch.Text).Trim().ToUpper()))
            {
                txtCarId.Text = CE.Global.General.GetCarId(Server.HtmlEncode(txtSearch.Text).Trim());
                DataTable _dtCarCustomer = new DataTable();
                _dtCarCustomer = CheckCarId(txtCarId.Text);
                if (_dtCarCustomer != null && _dtCarCustomer.Rows.Count > 0)
                {
                    txtCarId.Text = _dtCarCustomer.Rows[0]["CarId"].ToString();
                    txtUserId.Text = _dtCarCustomer.Rows[0]["RefCEUserId"].ToString();
                    lblTESCO200.Text = _dtCarCustomer.Rows[0]["Info8"].ToString();

                    if (lblTESCO200.Text == "TESCO200")
                    {
                        chkPromotion.Checked = true;
                    }
                }

                if (txtCarId.Text != string.Empty && txtUserId.Text != string.Empty && txtCarId.Text != "0" && txtUserId.Text != "0")
                {
                    LoadApplicationDetails();

                    lblMailingStatus.Text = "0";
                    if (!CheckApplicationProcessStatus(lblUpRefNo.Text.Trim().ToUpper(), "MAILING"))
                    {
                        lblMailingStatus.Text = "1";
                    }
                }
                else
                {
                    lblSearchMessage.Text = Resources.General.CheckRefNo;
                    divCar.Visible = false;
                }
            }
            else
            {
                lblSearchMessage.Text = Resources.General.CheckRefNo;
                divCar.Visible = false;
            }
        }
        else if (Server.HtmlEncode(txtSearch.Text).Trim().Length > 1 && Server.HtmlEncode(txtSearch.Text).Trim().Length <= 4)
        {
            lblSearchMessage.Text = Resources.General.CheckRefNo;
            divCar.Visible = false;
        }
        lblLoadMessage.Text = string.Empty;
    }

    private void LoadDate()
    {
        Int32 intStartYear = dateTimeNow.Year - 50;
        Int32 intEndYear = dateTimeNow.Year + 50;
        if (intStartYear == 0) intStartYear = dateTimeNow.Year - 75;
        if (intEndYear == 0) intEndYear = dateTimeNow.Year + 20;

        ddlCommenceYear.Items.Clear();

        for (int i = intEndYear; i >= intStartYear; i--)
        {
            if (lblLangOption.Text == "1")
            {
                ddlCommenceYear.Items.Add(new ListItem((i + 543).ToString(), i.ToString()));
            }
            else if (lblLangOption.Text == "2")
            {
                ddlCommenceYear.Items.Add(i.ToString());
            }
        }
        lblLoadMessage.Text = string.Empty;
    }

    private void LoadOption()
    {
        if (Session[CE.Global.General.UserRole] != null)
        {
            if (Session[CE.Global.General.UserRole].ToString() == "100")
            {
                ddlOption.Items.Clear();
                ddlOption.Items.Add(new ListItem(Resources.CarInsurance.Select, "0"));
                ddlOption.Items.Add(new ListItem(Resources.CarInsurance.MoreDetails, "EDIT"));
                // Yui
                //ddlOption.Items.Add(new ListItem(Resources.CarInsurance.Payment, "PAYM"));
                ddlOption.Items.Add(new ListItem(Resources.CarInsurance.CancelRejectApplication, "ACNL"));
                ddlOption.SelectedIndex = 0;
            }
            else if (Session[CE.Global.General.UserRole].ToString() == "200")
            {
                ddlOption.Items.Clear();
                ddlOption.Items.Add(new ListItem(Resources.CarInsurance.Select, "0"));
                ddlOption.Items.Add(new ListItem(Resources.CarInsurance.MoreDetails, "EDIT"));
                ddlOption.Items.Add(new ListItem(Resources.CarInsurance.Payment, "PAYM"));
                ddlOption.Items.Add(new ListItem(Resources.CarInsurance.UploadFile, "UPLD"));
                ddlOption.Items.Add(new ListItem(Resources.CarInsurance.CancelRejectApplication, "ACNL"));
                ddlOption.SelectedIndex = 0;
            }
            else
            {
                ddlOption.Items.Clear();
                ddlOption.Items.Add(new ListItem(Resources.CarInsurance.Select, "0"));
                ddlOption.Items.Add(new ListItem(Resources.CarInsurance.MoreDetails, "EDIT"));
                ddlOption.Items.Add(new ListItem(Resources.CarInsurance.Payment, "PAYM"));
                ddlOption.Items.Add(new ListItem(Resources.CarInsurance.UploadFile, "UPLD"));
                ddlOption.Items.Add(new ListItem(Resources.CarInsurance.CancelRejectApplication, "ACNL"));
                ddlOption.SelectedIndex = 0;
            }
            lblLoadMessage.Text = string.Empty;
        }

    }

    public void LoadApplicationDetails()
    {
        ClearFields();
        if (txtLastQuoteRefNo.Text != txtSearch.Text)
        {
            txtLastStep.Text = "";
            txtLastQuoteRefNo.Text = "";
        }
        lblNonGGStatus.Text = "0";
        string _ProviderRefCode = txtSearch.Text.Trim();
        string PID = "0";
        string LYPID = "0";
        if (_ProviderRefCode.Substring(0, 2) == "GG")
        {
            PID = _ProviderRefCode.Substring(2, 2);
        }
        _ProviderRefCode = _ProviderRefCode.Substring(0, 3);
        DataSet _dsApplication = new DataSet();
        NonGGPackageDB _nonggpackagedb = new NonGGPackageDB();
        
        _dsApplication = _nonggpackagedb.GetCarDetails(Convert.ToInt64(txtCarId.Text.Trim()), Convert.ToInt64(txtUserId.Text.Trim()));
        if (_dsApplication != null && _dsApplication.Tables.Count > 0 && _dsApplication.Tables[0].Rows.Count > 0)
        {
            txtUserTypeId.Text = _dsApplication.Tables[0].Rows[0]["UsrTypeId"].ToString();
            if (_dsApplication != null && _dsApplication.Tables.Count > 2 && _dsApplication.Tables[2].Rows.Count > 0)
            {
                DateTime _LastUpdateDate = new DateTime();
                _LastUpdateDate = Convert.ToDateTime(_dsApplication.Tables[2].Rows[0]["ModifiedDate"].ToString());
                lblLastUpdate.Text = Resources.General.LastUpdated + " : " + _LastUpdateDate.ToString("dd/MMM/yyyy hh:mm tt");
            }
            else
            {
                lblLastUpdate.Text = Resources.General.HaveNotSubmit;
            }

            lblSearchMessage.Text = "";
            if (_dsApplication != null && _dsApplication.Tables.Count > 2 && _dsApplication.Tables[2].Rows.Count > 0)
            {
                divCar.Visible = true;
                LoadNonGGApplicationDetails(_dsApplication);
            }
            else if (_dsApplication != null && _dsApplication.Tables.Count > 2 && _dsApplication.Tables[2].Rows.Count == 0)
            {
                #region Assign Values
                bool ProviderStatus = false;
                if (PID != "0" && _dsApplication.Tables[0].Rows[0]["CXBrokerProviderId"].ToString() == PID)
                {
                    ProviderStatus = true;
                }
                else if (_dsApplication.Tables[0].Rows[0]["CXBrokerProviderId"].ToString() == CE.Global.General.GetProviderId(_ProviderRefCode))
                {
                    ProviderStatus = true;
                }
                if (ProviderStatus == true)
                {
                    if (_dsApplication.Tables[0].Rows[0]["CXBrokerProviderId"].ToString() == "43")
                    {
                        trInsurerEmail.Visible = true;
                        rfvInsurerEmail.Enabled = true;
                        revInsurerEmail.Enabled = true;
                        txtInsurerEmail.Text = "support@gluaygluay.com";
                    }
                    else
                    {
                        trInsurerEmail.Visible = false;
                        rfvInsurerEmail.Enabled = false;
                        revInsurerEmail.Enabled = false;
                        txtInsurerEmail.Text = "";
                    }
                    divCar.Visible = true;
                    ddlCustomerType.SelectedIndex = 0;
                    chkIsCreditCardOwner.Checked = false;
                    if (_dsApplication.Tables[0].Rows[0]["Ninfo5"] != DBNull.Value && _dsApplication.Tables[0].Rows[0]["Ninfo5"].ToString() != string.Empty)
                    {
                        if (_dsApplication.Tables[0].Rows[0]["Ninfo5"].ToString() == "1")
                        {
                            chkIsCreditCardOwner.Checked = true;
                        }
                    }
                    if (_dsApplication.Tables[0].Rows[0]["Info7"] != DBNull.Value && _dsApplication.Tables[0].Rows[0]["Info7"].ToString() != string.Empty)
                    {
                        if (_dsApplication.Tables[0].Rows[0]["Info6"] != DBNull.Value && _dsApplication.Tables[0].Rows[0]["Info6"].ToString() != string.Empty)
                        {
                            txtLastYearCarId.Text = _dsApplication.Tables[0].Rows[0]["Info6"].ToString();
                        }
                        lblLastYearRefNo.Text = _dsApplication.Tables[0].Rows[0]["Info7"].ToString();
                        txtLastYearRefNo.Text = lblLastYearRefNo.Text;

                        lblLastYearPolicyNo.Text = string.Empty;
                        if (txtLastYearRefNo.Text.Trim().Length > 0)
                        {
                            lblRenewalMessage.Text = "Renewal App Details. Last Year Ref.No [ " + txtLastYearRefNo.Text + " ]";
                            ClientScript.RegisterStartupScript(lblLastUpdate.GetType(), "DownloadPremiumAlert", "alert('" + lblRenewalMessage.Text + "!');", true);


                            string _LstYrProviderRefCode = txtLastYearRefNo.Text.Trim();
                            if (_LstYrProviderRefCode.Substring(0, 2) == "GG")
                            {
                                LYPID = _LstYrProviderRefCode.Substring(2, 2);
                            }
                            _LstYrProviderRefCode = _LstYrProviderRefCode.Substring(0, 3);
                            bool LYProviderStatus = false;
                            if (PID != "0" && LYPID != "0" && PID == LYPID)
                            {
                                LYProviderStatus = true;
                            }
                            else if (CE.Global.General.GetProviderId(_ProviderRefCode) == CE.Global.General.GetProviderId(_LstYrProviderRefCode))
                            {
                                LYProviderStatus = true;
                            }
                            if (LYProviderStatus == true)
                            {
                                ddlApplicationType.Items.Clear();
                                ddlApplicationType.Items.Add(new ListItem(Resources.Proposal.AppTypeRenewalSameInsurer, "REN"));
                                ddlApplicationType.Text = "REN";
                                ddlApplicationType_SelectedIndexChanged(null, null);
                                lblLastYearPolicyNo.Text = GetLastYearPolicyNo(txtLastYearCarId.Text, txtUserId.Text);
                                txtLastYearPolicyNo.Text = lblLastYearPolicyNo.Text;
                            }
                            else
                            {
                                ddlApplicationType.Items.Clear();
                                ddlApplicationType.Items.Add(new ListItem(Resources.Proposal.AppTypeRenewalOtherInsurer, "RNO"));
                                ddlApplicationType.Text = "RNO";
                                ddlApplicationType_SelectedIndexChanged(null, null);
                            }
                        }
                        else
                        {
                            ddlApplicationType.Items.Clear();
                            ddlApplicationType.Items.Add(new ListItem(Resources.Proposal.AppTypeNew, "NEW"));
                            ddlApplicationType.Items.Add(new ListItem(Resources.Proposal.AppTypeChangeBroker, "CHB"));
                        }
                    }

                    if (_dsApplication.Tables[0].Rows[0]["ModificationAmount"] != DBNull.Value && _dsApplication.Tables[0].Rows[0]["ModificationAmount"].ToString() != string.Empty)
                    {
                        trModificationAmount.Visible = true;
                        txtModificationAmount.Text = _dsApplication.Tables[0].Rows[0]["ModificationAmount"].ToString();
                    }
                    else
                    {
                        trModificationAmount.Visible = false;
                        txtModificationAmount.Text = "";
                    }

                    if (_dsApplication != null && _dsApplication.Tables.Count > 4 && _dsApplication.Tables[4].Rows.Count > 0)
                    {
                        if (_dsApplication.Tables[4].Rows[0]["Name"] != DBNull.Value && _dsApplication.Tables[4].Rows[0]["Name"].ToString() != string.Empty)
                        {
                            txtCustomerName.Text = _dsApplication.Tables[4].Rows[0]["Name"].ToString();
                        }
                        else
                        {
                            txtCustomerName.Text = _dsApplication.Tables[0].Rows[0]["InsuredPerson"].ToString();
                        }
                    }
                    else
                    {
                        txtCustomerName.Text = _dsApplication.Tables[0].Rows[0]["InsuredPerson"].ToString();
                    }
                    lblUpApplicantName.Text = _dsApplication.Tables[0].Rows[0]["InsuredPerson"].ToString();
                    txtInsuredPerson.Text = _dsApplication.Tables[0].Rows[0]["InsuredPerson"].ToString();
                    txtContactNumber.Text = _dsApplication.Tables[0].Rows[0]["Mobile"].ToString();
                    if (_dsApplication.Tables[0].Rows[0]["OfficePhoneNo"] != DBNull.Value && _dsApplication.Tables[0].Rows[0]["OfficePhoneNo"].ToString() != string.Empty)
                    {
                        txtOtherContactNumber.Text = _dsApplication.Tables[0].Rows[0]["OfficePhoneNo"].ToString();
                    }
                    txtProviderId.Text = _dsApplication.Tables[0].Rows[0]["CXBrokerProviderId"].ToString();
                    LoadLableColor();
                    txtNewQuoteRefNo.Text = CE.Global.General.GetReferenceNumber(txtCarId.Text.Trim(), txtProviderId.Text.Trim());
                    if (txtGG.Text.Trim() == "GGSPECIAL")
                    {
                        txtNewQuoteRefNo.Text = CE.Global.General.GetGGReferenceNumber(txtCarId.Text.Trim(), txtProviderId.Text.Trim());
                    }

                    txtUserId.Text = _dsApplication.Tables[0].Rows[0]["RefCEUserId"].ToString();
                    txtCarModelYear.Text = _dsApplication.Tables[0].Rows[0]["ManufactYear"].ToString();
                    txtCarMakeModel.Text = _dsApplication.Tables[0].Rows[0]["MakeModelDesc"].ToString();
                    if (_dsApplication.Tables[0].Rows[0]["InsuranceType"] != DBNull.Value)
                    {
                        ddlInsuranceType.Text = _dsApplication.Tables[0].Rows[0]["InsuranceType"].ToString();
                    }
                    //Yui@22/01/2015
                    chkMile.Checked = false;
                    if (_dsApplication.Tables[0].Rows[0]["Mile"] != DBNull.Value)
                    {
                        chkMile.Checked = bool.Parse(_dsApplication.Tables[0].Rows[0]["Mile"].ToString());
                    }
                    if (_dsApplication.Tables[0].Rows[0]["VehicleType"] != DBNull.Value)
                    {
                        ddlVehicleType.Text = _dsApplication.Tables[0].Rows[0]["VehicleType"].ToString();
                    }
                    if (_dsApplication.Tables[0].Rows[0]["GarageType"] != DBNull.Value)
                    {
                        ddlGarageType.Text = _dsApplication.Tables[0].Rows[0]["GarageType"].ToString();
                    }
                    ddlNCB.Text = _dsApplication.Tables[0].Rows[0]["NCDPercent"].ToString();

                    string _sumInsured = string.Empty;
                    _sumInsured = _dsApplication.Tables[0].Rows[0]["SumInsured"].ToString();
                    decimal _outSumInsurred = 0;
                    if (!decimal.TryParse(_sumInsured, out _outSumInsurred))
                    {
                        _sumInsured = "0";
                    }
                    else
                    {
                        _sumInsured = _outSumInsurred.ToString("#0");
                    }
                    txtSumInsured.Text = _sumInsured.ToString();// _dsApplication.Tables[0].Rows[0]["SumInsured"].ToString();
                    txtInsurancePremium.Text = _dsApplication.Tables[0].Rows[0]["Premium"].ToString();
                    txtTotalPremium.Text = _dsApplication.Tables[0].Rows[0]["TotalPremium"].ToString();
                    txtCollectedAmount.Text = _dsApplication.Tables[0].Rows[0]["FinalAnnualPremium"].ToString();
                    lblUpPremium.Text = _dsApplication.Tables[0].Rows[0]["FinalAnnualPremium"].ToString();
                    txtCTPL.Text = _dsApplication.Tables[0].Rows[0]["CTPL"].ToString();
                    txtCurrentInsurer.Text = _dsApplication.Tables[0].Rows[0]["CurrentInsurer"].ToString();
                    txtPlateNumber.Text = _dsApplication.Tables[0].Rows[0]["CarPlate"].ToString();

                    if (_dsApplication.Tables[0].Rows[0]["IsCTPL"].ToString() == "False" || _dsApplication.Tables[0].Rows[0]["IsCTPL"].ToString() == "0")
                    {
                        ddlCTPL.Text = "0";
                    }
                    else
                    {
                        ddlCTPL.Text = "1";
                    }

                    if (_dsApplication.Tables[0].Rows[0]["Gender"] != DBNull.Value)
                    {
                        ddlGender.Text = _dsApplication.Tables[0].Rows[0]["Gender"].ToString();
                    }
                    if (_dsApplication.Tables[0].Rows[0]["OccupationId"] != DBNull.Value)
                    {
                        ddlOccupation.Text = _dsApplication.Tables[0].Rows[0]["OccupationId"].ToString();
                    }
                    txtInsuranceCompany.Text = _dsApplication.Tables[0].Rows[0]["CompanyName"].ToString();
                    txtPackage.Text = _dsApplication.Tables[0].Rows[0]["Package"].ToString();
                    ddlNamedDriver.Text = _dsApplication.Tables[0].Rows[0]["NoOfDriver"].ToString();
                    ddlNamedDriver_SelectedIndexChanged(null, null);
                    txtDriverId1.Text = "0";
                    txtDriverId2.Text = "0";
                    DateTime Commdate = dateTimeNow;
                    if (_dsApplication.Tables[0].Rows[0]["CoverageCommenceDate"] != DBNull.Value && _dsApplication.Tables[0].Rows[0]["CoverageCommenceDate"].ToString() != string.Empty)
                    {
                        Commdate = Convert.ToDateTime(_dsApplication.Tables[0].Rows[0]["CoverageCommenceDate"].ToString());
                        txtCommencementDate.Text = Convert.ToDateTime(_dsApplication.Tables[0].Rows[0]["CoverageCommenceDate"]).ToString("dd/MMM/yyyy");
                    }
                    AssignDate(Commdate.Day, ddlCommenceDay);
                    AssignMonth(Commdate.Month, ddlCommenceMonth);
                    AssignYear(Commdate.Year, ddlCommenceYear);

                    AssignDate(Commdate.Day, ddlPolicyDay);
                    AssignMonth(Commdate.Month, ddlPolicyMonth);
                    AssignYear(Commdate.Year, ddlPolicyYear);

                    DateTime DOB = dateTimeNow;
                    if (_dsApplication.Tables[0].Rows[0]["DOB"] != DBNull.Value && _dsApplication.Tables[0].Rows[0]["DOB"].ToString() != string.Empty)
                    {
                        DOB = Convert.ToDateTime(_dsApplication.Tables[0].Rows[0]["DOB"].ToString());
                    }
                    AssignDate(DOB.Day, ddlDOBDay);
                    AssignMonth(DOB.Month, ddlDOBMonth);
                    AssignYear(DOB.Year, ddlDOBYear);
                    DateTime DriverDOB1 = dateTimeNow.AddYears(-20);
                    DateTime DriverDOB2 = dateTimeNow.AddYears(-20);
                    if (_dsApplication.Tables.Count > 1)
                    {
                        if (_dsApplication.Tables[1].Rows.Count > 0 && _dsApplication.Tables[1].Rows[0]["DOB"] != DBNull.Value && _dsApplication.Tables[1].Rows[0]["DOB"].ToString() != string.Empty)
                        {
                            DriverDOB1 = Convert.ToDateTime(_dsApplication.Tables[1].Rows[0]["DOB"].ToString());
                        }
                        if (_dsApplication.Tables[1].Rows.Count > 1 && _dsApplication.Tables[1].Rows[1]["DOB"] != DBNull.Value && _dsApplication.Tables[1].Rows[1]["DOB"].ToString() != string.Empty)
                        {
                            DriverDOB2 = Convert.ToDateTime(_dsApplication.Tables[1].Rows[1]["DOB"].ToString());
                        }
                    }
                    AssignDate(DriverDOB1.Day, ddlDriver1DOBDay);
                    AssignMonth(DriverDOB1.Month, ddlDriver1DOBMonth);
                    AssignYear(DriverDOB1.Year, ddlDriver1DOBYear);
                    AssignDate(DriverDOB2.Day, ddlDriver2DOBDay);
                    AssignMonth(DriverDOB2.Month, ddlDriver2DOBMonth);
                    AssignYear(DriverDOB2.Year, ddlDriver2DOBYear);
                    if (ddlNamedDriver.Text == "0")
                    {
                        rfvDriverFirst.Enabled = false;
                        revDriverFirst.Enabled = false;
                        rfvDriver1IDNo.Enabled = false;
                        rfvDriver1LicenseNo.Enabled = false;
                        rfvDriverTwo.Enabled = false;
                        revDriverTwo.Enabled = false;
                        rfvDriver2IDNo.Enabled = false;
                        rfvDriver2LicenseNo.Enabled = false;
                    }
                    if (ddlNamedDriver.Text == "1")
                    {
                        rfvDriverFirst.Enabled = true;
                        revDriverFirst.Enabled = true;
                        rfvDriver1IDNo.Enabled = true;
                        rfvDriver1LicenseNo.Enabled = true;
                        rfvDriverTwo.Enabled = false;
                        revDriverTwo.Enabled = false;
                        rfvDriver2IDNo.Enabled = false;
                        rfvDriver2LicenseNo.Enabled = false;
                    }
                    if (ddlNamedDriver.Text == "2")
                    {
                        rfvDriverFirst.Enabled = true;
                        revDriverFirst.Enabled = true;
                        rfvDriver1IDNo.Enabled = true;
                        rfvDriver1LicenseNo.Enabled = true;
                        rfvDriverTwo.Enabled = true;
                        revDriverTwo.Enabled = true;
                        rfvDriver2IDNo.Enabled = true;
                        rfvDriver2LicenseNo.Enabled = true;
                    }
                    if (_dsApplication.Tables.Count > 4 && _dsApplication.Tables[4].Rows.Count > 0)
                    {
                        if (_dsApplication.Tables[4].Rows[0]["Name"] != DBNull.Value && _dsApplication.Tables[4].Rows[0]["Name"].ToString() != string.Empty)
                        {
                            txtCustomerName.Text = _dsApplication.Tables[4].Rows[0]["Name"].ToString();
                        }
                        if (_dsApplication.Tables[4].Rows[0]["BeneficiaryName"] != DBNull.Value)
                            txtBeneficiary.Text = _dsApplication.Tables[4].Rows[0]["BeneficiaryName"].ToString();

                        txtCurrentAddress.Text = _dsApplication.Tables[4].Rows[0]["PresentAddress"].ToString();
                        txtSubDistrict.Text = _dsApplication.Tables[4].Rows[0]["SubDistrict"].ToString();
                        txtStateProvince.Text = _dsApplication.Tables[4].Rows[0]["District"].ToString();
                        txtProvince.Text = _dsApplication.Tables[4].Rows[0]["Province"].ToString();
                        txtPostalCode.Text = _dsApplication.Tables[4].Rows[0]["PostalCode"].ToString();

                        if (_dsApplication.Tables[4].Rows[0]["IsMailingAddressDiff"] != DBNull.Value && 
                            _dsApplication.Tables[4].Rows[0]["IsMailingAddressDiff"].ToString() == "True")
                        {
                            //From Web
                            trSameAddress1.Style.Add("display", "");
                            trSameAddress2.Style.Add("display", "");
                            trSameAddress3.Style.Add("display", "");
                            chkSameAddress.Checked = false;
                            txtSameAddress.Text = _dsApplication.Tables[4].Rows[0]["MailingAddress"].ToString();
                            txtSameAddrSubDistrict.Text = _dsApplication.Tables[4].Rows[0]["MailingSubDistrict"].ToString();
                            txtSameAddrStateProvince.Text = _dsApplication.Tables[4].Rows[0]["MailingDistrict"].ToString();
                            txtSameAddrProvince.Text = _dsApplication.Tables[4].Rows[0]["MailingProvince"].ToString();
                            txtSameAddrPostalCode.Text = _dsApplication.Tables[4].Rows[0]["MailingPostalCode"].ToString();
                            if (_dsApplication.Tables[4].Columns.Contains("MailingName"))
                                txtSameAddrName.Text = _dsApplication.Tables[4].Rows[0]["MailingName"].ToString();
                            else if (_dsApplication.Tables[4].Columns.Contains("Name"))
                                txtSameAddrName.Text = _dsApplication.Tables[4].Rows[0]["Name"].ToString();
                            refSameAddrName.Enabled = true;
                            refSameAddress.Enabled = true;
                            refSameAddrSubDistrict.Enabled = true;
                            refSameAddrStateProvince.Enabled = true;
                            refSameAddrProvince.Enabled = true;
                            refSameAddrPostalCode.Enabled = true;
                        }
                        else
                        {
                            trSameAddress1.Style.Add("display", "none");
                            trSameAddress2.Style.Add("display", "none");
                            trSameAddress3.Style.Add("display", "none");
                            chkSameAddress.Checked = true;
                            txtSameAddress.Text = "";
                            txtSameAddrSubDistrict.Text = "";
                            txtSameAddrStateProvince.Text = "";
                            txtSameAddrProvince.Text = "";
                            txtSameAddrPostalCode.Text = "";
                            txtSameAddrName.Text = "";
                            refSameAddrName.Enabled = false;
                            refSameAddress.Enabled = false;
                            refSameAddrSubDistrict.Enabled = false;
                            refSameAddrStateProvince.Enabled = false;
                            refSameAddrProvince.Enabled = false;
                            refSameAddrPostalCode.Enabled = false;
                        }

                        if (_dsApplication.Tables.Count > 5 && _dsApplication.Tables[5].Rows.Count > 0)
                        {
                            txtPackage.Text = _dsApplication.Tables[5].Rows[0]["CoverTypeDesc"].ToString();
                        }
                        if (_dsApplication.Tables[4].Rows[0]["EngineNumber"] != DBNull.Value)
                            txtEngineNumber.Text = _dsApplication.Tables[4].Rows[0]["EngineNumber"].ToString();
                        if (_dsApplication.Tables[4].Rows[0]["ChassisNumber"] != DBNull.Value)
                            txtChassisNumber.Text = _dsApplication.Tables[4].Rows[0]["ChassisNumber"].ToString();
                        if (_dsApplication.Tables[4].Rows[0]["CarPlate"] != DBNull.Value)
                            txtPlateNumber.Text = _dsApplication.Tables[4].Rows[0]["CarPlate"].ToString().ToUpper();
                        if (_dsApplication.Tables[4].Rows[0]["CarPlateProvince"] != DBNull.Value)
                            txtRegistrationProvince.Text = _dsApplication.Tables[4].Rows[0]["CarPlateProvince"].ToString();

                        DateTime _CreateDate = Convert.ToDateTime(_dsApplication.Tables[4].Rows[0]["CreatedDate"].ToString());
                        if (ddlApplicationDay.Items.Count > 0)
                            ddlApplicationDay.Items.Clear();
                        ddlApplicationDay.Items.Add(new ListItem(_CreateDate.Day.ToString("00"), _CreateDate.Day.ToString("00")));
                        if (ddlApplicationMonth.Items.Count > 0)
                            ddlApplicationMonth.Items.Clear();
                        ddlApplicationMonth.Items.Add(new ListItem(_CreateDate.Month.ToString("00"), _CreateDate.Month.ToString("00")));
                        if (ddlApplicationYear.Items.Count > 0)
                            ddlApplicationYear.Items.Clear();
                        ddlApplicationYear.Items.Add(new ListItem(_CreateDate.Year.ToString("0000"), _CreateDate.Year.ToString("0000")));
                    }
                    else
                    {
                        DateTime _CreateDate = Convert.ToDateTime(_dsApplication.Tables[0].Rows[0]["CreatedDate"].ToString());
                        if (ddlApplicationDay.Items.Count > 0)
                            ddlApplicationDay.Items.Clear();
                        ddlApplicationDay.Items.Add(new ListItem(_CreateDate.Day.ToString("00"), _CreateDate.Day.ToString("00")));
                        if (ddlApplicationMonth.Items.Count > 0)
                            ddlApplicationMonth.Items.Clear();
                        ddlApplicationMonth.Items.Add(new ListItem(_CreateDate.Month.ToString("00"), _CreateDate.Month.ToString("00")));
                        if (ddlApplicationYear.Items.Count > 0)
                            ddlApplicationYear.Items.Clear();
                        ddlApplicationYear.Items.Add(new ListItem(_CreateDate.Year.ToString("0000"), _CreateDate.Year.ToString("0000")));
                    }

                    // Renew Ext Com Date
                    int intStartYear = dateTimeNow.Year - 1;
                    int intEndYear = dateTimeNow.Year + 1;
                    LoadDate(ddlExtComDay);
                    ddlExtComDay.Items.Insert(0, new ListItem("", ""));
                    LoadMonth(ddlExtComMonth);
                    ddlExtComMonth.Items.Insert(0, new ListItem("", ""));
                    LoadYear(ddlExtComYear, intStartYear, intEndYear);
                    ddlExtComYear.Items.Insert(0, new ListItem("", ""));

                    MyDatabase _myDb = new MyDatabase();
                    string _strSelect = "SELECT CD.Dinfo2 "
                            + " FROM tblCarPolicy CP INNER JOIN tblCarDetailTH CD ON CD.CarId = CP.CECarId "
                            + " WHERE CP.RefCEUserId = " + txtUserId.Text.Trim() + " AND CP.CECarId= " + txtCarId.Text.Trim();
                    object _extDate = _myDb.ExecuteScalarSqlStatement(_strSelect);
                    if (_extDate != null && _extDate.ToString() != "")
                    {
                        chkExtComDate.Checked = true;
                        ddlExtComDay.Style.Add("visibility", "visible");
                        ddlExtComMonth.Style.Add("visibility", "visible");
                        ddlExtComYear.Style.Add("visibility", "visible");
                        DateTime extDate = Convert.ToDateTime(_extDate);

                        ddlExtComDay.SelectedIndex = ddlExtComDay.Items.IndexOf(ddlExtComDay.Items.FindByValue(extDate.ToString("dd")));
                        ddlExtComMonth.SelectedIndex = ddlExtComMonth.Items.IndexOf(ddlExtComMonth.Items.FindByValue(extDate.ToString("MM")));
                        ddlExtComYear.SelectedIndex = ddlExtComYear.Items.IndexOf(ddlExtComYear.Items.FindByValue(extDate.ToString("yyyy")));
                    }
                    else
                    {
                        ddlExtComDay.Style.Add("visibility", "hidden");
                        ddlExtComMonth.Style.Add("visibility", "hidden");
                        ddlExtComYear.Style.Add("visibility", "hidden");
                    }
                    //*******************
                
                }
                #endregion
            }
            else
            {
                lblSearchMessage.Text = Resources.General.CheckRefNo;
                divCar.Visible = false;
            }
            LoadLastYearApplicationDetails();
        }
        else
        {
            lblSearchMessage.Text = Resources.General.CheckRefNo;
            divCar.Visible = false;
        }
        if (txtUserId.Text != "" && txtProviderId.Text != "")
        {
            GetCarMoreDetails();
        }
    }

    public void LoadNonGGApplicationDetails(DataSet dsApplication)
    {
        //ClearFields();
        string _ProviderRefCode = txtSearch.Text.Trim();
        string PID = "0";
        if (_ProviderRefCode.Substring(0, 2) == "GG")
        {
            PID = _ProviderRefCode.Substring(2, 2);
        }
        _ProviderRefCode = _ProviderRefCode.Substring(0, 3);
        if (dsApplication != null && dsApplication.Tables.Count > 2 && dsApplication.Tables[2].Rows.Count > 0)
        {
            lblSearchMessage.Text = "";
            lblNonGGStatus.Text = "1";
            #region Assign Values
            
            if (dsApplication.Tables[2].Rows[0]["ProviderCompanyId"].ToString() == "43")
            {
                trInsurerEmail.Visible = true;
                rfvInsurerEmail.Enabled = true;
                revInsurerEmail.Enabled = true;
                if (dsApplication.Tables[2].Rows[0]["Info3"] != DBNull.Value && dsApplication.Tables[2].Rows[0]["Info3"].ToString() != string.Empty)
                {
                    txtInsurerEmail.Text = dsApplication.Tables[2].Rows[0]["Info3"].ToString();
                }
                else
                {
                    txtInsurerEmail.Text = "support@gluaygluay.com";
                }
            }
            else
            {
                trInsurerEmail.Visible = false;
                rfvInsurerEmail.Enabled = false;
                revInsurerEmail.Enabled = false;
                txtInsurerEmail.Text = "";
            }
            lblAgentId.Text = "0";
            lblAdminId.Text = "0";
            chkIsCreditCardOwner.Checked = false;
            if (dsApplication.Tables[0].Rows[0]["Ninfo5"] != DBNull.Value && dsApplication.Tables[0].Rows[0]["Ninfo5"].ToString() != string.Empty)
            {
                if (dsApplication.Tables[0].Rows[0]["Ninfo5"].ToString() == "1")
                {
                    chkIsCreditCardOwner.Checked = true;
                }
            }
            chkPromotion.Checked = false;
            if (dsApplication.Tables[2].Rows[0]["PromotionCode"] != DBNull.Value && dsApplication.Tables[2].Rows[0]["PromotionCode"].ToString() != string.Empty)
            {
                if (dsApplication.Tables[2].Rows[0]["PromotionCode"].ToString() == "1")
                {
                    chkPromotion.Checked = true;
                }
            }
            if (dsApplication.Tables[0].Rows[0]["Info7"] != DBNull.Value && dsApplication.Tables[0].Rows[0]["Info7"].ToString() != string.Empty)
            {
                lblLastYearRefNo.Text = dsApplication.Tables[0].Rows[0]["Info7"].ToString();
                txtLastYearRefNo.Text = lblLastYearRefNo.Text;
                if (txtLastYearRefNo.Text.Trim().Length > 0)
                {
                    lblRenewalMessage.Text = "Renewal App Details. Last Year Ref.No [ " + txtLastYearRefNo.Text + " ]";
                    ClientScript.RegisterStartupScript(lblLastUpdate.GetType(), "DownloadPremiumAlert", "alert('" + lblRenewalMessage.Text + "!');", true);
                }
            }
            if (dsApplication.Tables[2].Rows[0]["Info1"] != DBNull.Value && dsApplication.Tables[2].Rows[0]["Info1"].ToString() != string.Empty)
            {
                if (dsApplication.Tables[2].Rows[0]["Info1"].ToString().ToUpper() == "REN")
                {
                    ddlApplicationType.Items.Clear();
                    ddlApplicationType.Items.Add(new ListItem(Resources.Proposal.AppTypeRenewalSameInsurer, "REN"));
                    ddlApplicationType.Text = dsApplication.Tables[2].Rows[0]["Info1"].ToString();
                    ddlApplicationType_SelectedIndexChanged(null, null);
                }
                else if (dsApplication.Tables[2].Rows[0]["Info1"].ToString().ToUpper() == "RNO")
                {
                    ddlApplicationType.Items.Clear();
                    ddlApplicationType.Items.Add(new ListItem(Resources.Proposal.AppTypeRenewalOtherInsurer, "RNO"));
                    ddlApplicationType.Text = dsApplication.Tables[2].Rows[0]["Info1"].ToString();
                    ddlApplicationType_SelectedIndexChanged(null, null);
                }
                else
                {
                    ddlApplicationType.Items.Clear();
                    ddlApplicationType.Items.Add(new ListItem(Resources.Proposal.AppTypeNew, "NEW"));
                    ddlApplicationType.Items.Add(new ListItem(Resources.Proposal.AppTypeChangeBroker, "CHB"));
                    ddlApplicationType.Text = dsApplication.Tables[2].Rows[0]["Info1"].ToString();
                    ddlApplicationType_SelectedIndexChanged(null, null);
                }
            }
            if (dsApplication.Tables[2].Rows[0]["Info2"] != DBNull.Value && dsApplication.Tables[2].Rows[0]["Info2"].ToString() != string.Empty)
            {
                txtLastYearPolicyNo.Text = dsApplication.Tables[2].Rows[0]["Info2"].ToString();
                lblLastYearPolicyNo.Text = dsApplication.Tables[2].Rows[0]["Info2"].ToString();
            }

            if (dsApplication.Tables[2].Rows[0]["Info4"] != DBNull.Value && dsApplication.Tables[2].Rows[0]["Info4"].ToString() != string.Empty)
            {
                trModificationAmount.Visible = true;
                txtModificationAmount.Text = dsApplication.Tables[2].Rows[0]["Info4"].ToString();
            }
            else
            {
                trModificationAmount.Visible = false;
                txtModificationAmount.Text = "";
            }

            if (dsApplication.Tables[2].Rows[0]["Info8"] != DBNull.Value && dsApplication.Tables[2].Rows[0]["Info8"].ToString() != string.Empty)
            {
                txtAgentRemarkDetails.Text = dsApplication.Tables[2].Rows[0]["Info8"].ToString();
            }
            else
            {
                txtAgentRemarkDetails.Text = "";
            }


            if (dsApplication.Tables[2].Rows[0]["AgentId"] != DBNull.Value && dsApplication.Tables[2].Rows[0]["AgentId"].ToString() != string.Empty)
            {
                lblAgentId.Text = dsApplication.Tables[2].Rows[0]["AgentId"].ToString();
            }
            if (dsApplication.Tables[2].Rows[0]["AdminId"] != DBNull.Value && dsApplication.Tables[2].Rows[0]["AdminId"].ToString() != string.Empty)
            {
                lblAdminId.Text = dsApplication.Tables[2].Rows[0]["AdminId"].ToString();
            }
            txtCarModelYear.Text = dsApplication.Tables[2].Rows[0]["CarYear"].ToString();
            txtCarMakeModel.Text = dsApplication.Tables[2].Rows[0]["CarModel"].ToString();
            if (dsApplication.Tables[2].Rows[0]["InsuranceType"] != DBNull.Value)
            {
                ddlInsuranceType.Text = dsApplication.Tables[2].Rows[0]["InsuranceType"].ToString();
            }
            //Yui@22/01/2015
            chkMile.Checked = false;
            if (dsApplication.Tables[2].Rows[0]["Ninfo5"] != DBNull.Value)
            {
                if (dsApplication.Tables[2].Rows[0]["Ninfo5"].ToString() == "1")
                    chkMile.Checked = true;
            }
            if (dsApplication.Tables[2].Rows[0]["VehicleType"] != DBNull.Value)
            {
                ddlVehicleType.Text = dsApplication.Tables[2].Rows[0]["VehicleType"].ToString();
            }
            if (dsApplication.Tables[2].Rows[0]["GarageType"] != DBNull.Value)
            {
                ddlGarageType.Text = dsApplication.Tables[2].Rows[0]["GarageType"].ToString();
            }
            DateTime Commdate = dateTimeNow;
            if (dsApplication.Tables[2].Rows[0]["CoverageStart"] != DBNull.Value && dsApplication.Tables[2].Rows[0]["CoverageStart"].ToString() != string.Empty)
            {
                Commdate = Convert.ToDateTime(dsApplication.Tables[2].Rows[0]["CoverageStart"].ToString());
                txtCommencementDate.Text = Convert.ToDateTime(dsApplication.Tables[2].Rows[0]["CoverageStart"]).ToString("dd/MMM/yyyy");
            }
            AssignDate(Commdate.Day, ddlCommenceDay);
            AssignMonth(Commdate.Month, ddlCommenceMonth);
            AssignYear(Commdate.Year, ddlCommenceYear);
            DateTime policy = dateTimeNow;
            if (dsApplication.Tables[2].Rows[0]["CTPLStart"] != DBNull.Value && dsApplication.Tables[2].Rows[0]["CTPLStart"].ToString() != string.Empty)
            {
                policy = Convert.ToDateTime(dsApplication.Tables[2].Rows[0]["CTPLStart"].ToString());
            }
            AssignDate(policy.Day, ddlPolicyDay);
            AssignMonth(policy.Month, ddlPolicyMonth);
            AssignYear(policy.Year, ddlPolicyYear);


            
            string _sumInsured = string.Empty;
            _sumInsured = dsApplication.Tables[2].Rows[0]["SumInsured"].ToString();
            decimal _outSumInsurred = 0;
            if (!decimal.TryParse(_sumInsured, out _outSumInsurred))
            {
                _sumInsured = "0";
            }
            else
            {
                _sumInsured = _outSumInsurred.ToString("#");
            }
            txtSumInsured.Text = _sumInsured.ToString();// dsApplication.Tables[2].Rows[0]["SumInsured"].ToString();
            txtInsurancePremium.Text = dsApplication.Tables[2].Rows[0]["Premium"].ToString();
            txtTotalPremium.Text = dsApplication.Tables[2].Rows[0]["TotalPremium"].ToString();
            txtCollectedAmount.Text = dsApplication.Tables[2].Rows[0]["FinalAnnualPremium"].ToString();
            lblUpPremium.Text = dsApplication.Tables[2].Rows[0]["FinalAnnualPremium"].ToString();
            txtCTPL.Text = dsApplication.Tables[2].Rows[0]["CTPL"].ToString();
            txtCurrentInsurer.Text = dsApplication.Tables[2].Rows[0]["CurrentInsurer"].ToString();
            
            if (dsApplication.Tables[2].Rows[0]["IsCTPL"].ToString() == "False" || dsApplication.Tables[2].Rows[0]["IsCTPL"].ToString() == "false" || dsApplication.Tables[2].Rows[0]["IsCTPL"].ToString() == "0")
            {
                ddlCTPL.Text = "0";
            }
            else
            {
                ddlCTPL.Text = "1";
            }
            
            txtInsuranceCompany.Text = dsApplication.Tables[0].Rows[0]["CompanyName"].ToString();
            
            txtEngineNumber.Text = dsApplication.Tables[2].Rows[0]["EngineNumber"].ToString();
            txtChassisNumber.Text = dsApplication.Tables[2].Rows[0]["ChassisNumber"].ToString();
            txtPlateNumber.Text = dsApplication.Tables[2].Rows[0]["CarPlate"].ToString();
            txtRegistrationProvince.Text = dsApplication.Tables[2].Rows[0]["CarPlateProvince"].ToString();
            ddlNCB.Text = dsApplication.Tables[2].Rows[0]["NCB"].ToString();

            
            txtProviderId.Text = dsApplication.Tables[0].Rows[0]["CXBrokerProviderId"].ToString();
            LoadLableColor();
            txtNewQuoteRefNo.Text = dsApplication.Tables[2].Rows[0]["QuoteRefNo"].ToString();
            txtUserId.Text = dsApplication.Tables[2].Rows[0]["RefCEUserId"].ToString();

            ddlCustomerType.Text = dsApplication.Tables[2].Rows[0]["CustomerType"].ToString();
            txtCustomerName.Text = dsApplication.Tables[2].Rows[0]["CustomerName"].ToString();
            txtPrefix.Text = dsApplication.Tables[2].Rows[0]["Title"].ToString();
            txtBeneficiary.Text = dsApplication.Tables[2].Rows[0]["Beneficiary"].ToString();
            txtInsuredPerson.Text = dsApplication.Tables[2].Rows[0]["Name"].ToString();
            txtContactNumber.Text = dsApplication.Tables[2].Rows[0]["ContactNo"].ToString();
            if (dsApplication.Tables[2].Rows[0]["OfficePhoneNo"] != DBNull.Value && dsApplication.Tables[2].Rows[0]["OfficePhoneNo"].ToString() != string.Empty)
            {
                txtOtherContactNumber.Text = dsApplication.Tables[2].Rows[0]["OfficePhoneNo"].ToString();
            }
            txtCitizenID.Text = "";
            if (dsApplication.Tables[2].Rows[0]["IdentificationNo"] != DBNull.Value && dsApplication.Tables[2].Rows[0]["IdentificationNo"].ToString() != string.Empty)
            {
                txtCitizenID.Text = dsApplication.Tables[2].Rows[0]["IdentificationNo"].ToString();
            }
            txtCurrentAddress.Text = dsApplication.Tables[2].Rows[0]["PresentAddress"].ToString();
            txtSubDistrict.Text = dsApplication.Tables[2].Rows[0]["SubDistrict"].ToString();
            txtStateProvince.Text = dsApplication.Tables[2].Rows[0]["District"].ToString();
            txtProvince.Text = dsApplication.Tables[2].Rows[0]["Province"].ToString();
            txtPostalCode.Text = dsApplication.Tables[2].Rows[0]["PostalCode"].ToString();

            if (dsApplication.Tables[2].Rows[0]["IsMailingAddressDiff"] != DBNull.Value &&
                dsApplication.Tables[2].Rows[0]["IsMailingAddressDiff"].ToString() == "True")
            {
                //From CRM
                trSameAddress1.Style.Add("display", "");
                trSameAddress2.Style.Add("display", "");
                trSameAddress3.Style.Add("display", "");
                chkSameAddress.Checked = false;
                txtSameAddress.Text = dsApplication.Tables[2].Rows[0]["MailingAddress"].ToString();
                txtSameAddrSubDistrict.Text = dsApplication.Tables[2].Rows[0]["MailingSubDistrict"].ToString();
                txtSameAddrStateProvince.Text = dsApplication.Tables[2].Rows[0]["MailingDistrict"].ToString();
                txtSameAddrProvince.Text = dsApplication.Tables[2].Rows[0]["MailingProvince"].ToString();
                txtSameAddrPostalCode.Text = dsApplication.Tables[2].Rows[0]["MailingPostalCode"].ToString();
                txtSameAddrName.Text = dsApplication.Tables[2].Rows[0]["MailingName"].ToString();
                refSameAddrName.Enabled = true;
                refSameAddress.Enabled = true;
                refSameAddrSubDistrict.Enabled = true;
                refSameAddrStateProvince.Enabled = true;
                refSameAddrProvince.Enabled = true;
                refSameAddrPostalCode.Enabled = true;
            }
            else
            {
                trSameAddress1.Style.Add("display", "none");
                trSameAddress2.Style.Add("display", "none");
                trSameAddress3.Style.Add("display", "none");
                chkSameAddress.Checked = true;
                txtSameAddress.Text = "";
                txtSameAddrSubDistrict.Text = "";
                txtSameAddrStateProvince.Text = "";
                txtSameAddrProvince.Text = "";
                txtSameAddrPostalCode.Text = "";
                txtSameAddrName.Text = "";
                refSameAddrName.Enabled = false;
                refSameAddress.Enabled = false;
                refSameAddrSubDistrict.Enabled = false;
                refSameAddrStateProvince.Enabled = false;
                refSameAddrProvince.Enabled = false;
                refSameAddrPostalCode.Enabled = false;
            }

            txtPackage.Text = dsApplication.Tables[2].Rows[0]["Package"].ToString();

            if (dsApplication.Tables[2].Rows[0]["Gender"] != DBNull.Value)
            {
                ddlGender.Text = dsApplication.Tables[2].Rows[0]["Gender"].ToString();
            }

            DateTime DOB = dateTimeNow;
            if (dsApplication.Tables[2].Rows[0]["DOB"] != DBNull.Value && dsApplication.Tables[2].Rows[0]["DOB"].ToString() != string.Empty)
            {
                DOB = Convert.ToDateTime(dsApplication.Tables[2].Rows[0]["DOB"].ToString());
            }
            AssignDate(DOB.Day, ddlDOBDay);
            AssignMonth(DOB.Month, ddlDOBMonth);
            AssignYear(DOB.Year, ddlDOBYear);
            DateTime DriverDOB1 = dateTimeNow.AddYears(-20);
            DateTime DriverDOB2 = dateTimeNow.AddYears(-20);
            ddlOccupation.Text = dsApplication.Tables[2].Rows[0]["Occupation"].ToString();
            ddlNamedDriver.Text = dsApplication.Tables[2].Rows[0]["NoOfDriver"].ToString();
            ddlNamedDriver_SelectedIndexChanged(null, null);
            if (ddlNamedDriver.Text == "0")
            {
                txtDriverId1.Text = "0";
                txtDriverId2.Text = "0";
            }
            else if (ddlNamedDriver.Text == "1")
            {
                txtDriverId2.Text = "0";
            }
            if (dsApplication.Tables.Count > 3)
            {
                if (dsApplication.Tables[3].Rows.Count > 0 && dsApplication.Tables[3].Rows[0]["DOB"] != DBNull.Value && dsApplication.Tables[3].Rows[0]["DOB"].ToString() != string.Empty)
                {
                    DriverDOB1 = Convert.ToDateTime(dsApplication.Tables[3].Rows[0]["DOB"].ToString());
                }
                if (dsApplication.Tables[3].Rows.Count > 1 && dsApplication.Tables[3].Rows[1]["DOB"] != DBNull.Value && dsApplication.Tables[3].Rows[1]["DOB"].ToString() != string.Empty)
                {
                    DriverDOB2 = Convert.ToDateTime(dsApplication.Tables[3].Rows[1]["DOB"].ToString());
                }
                if (dsApplication.Tables[3].Rows.Count > 0)
                {
                    txtDriverFirst.Text = dsApplication.Tables[3].Rows[0]["FullName"].ToString();
                    txtDriver1IDNo.Text = dsApplication.Tables[3].Rows[0]["IDNo"].ToString();
                    txtDriver1LicenseNo.Text = dsApplication.Tables[3].Rows[0]["DrivingLicenseNumber"].ToString();
                    txtDriverId1.Text = dsApplication.Tables[3].Rows[0]["CarDriverId"].ToString();
                }
                if (dsApplication.Tables[3].Rows.Count > 1)
                {
                    txtDriverTwo.Text = dsApplication.Tables[3].Rows[1]["FullName"].ToString();
                    txtDriver2IDNo.Text = dsApplication.Tables[3].Rows[1]["IDNo"].ToString();
                    txtDriver2LicenseNo.Text = dsApplication.Tables[3].Rows[1]["DrivingLicenseNumber"].ToString();
                    txtDriverId2.Text = dsApplication.Tables[3].Rows[1]["CarDriverId"].ToString();
                }
            }
            AssignDate(DriverDOB1.Day, ddlDriver1DOBDay);
            AssignMonth(DriverDOB1.Month, ddlDriver1DOBMonth);
            AssignYear(DriverDOB1.Year, ddlDriver1DOBYear);
            AssignDate(DriverDOB2.Day, ddlDriver2DOBDay);
            AssignMonth(DriverDOB2.Month, ddlDriver2DOBMonth);
            AssignYear(DriverDOB2.Year, ddlDriver2DOBYear);

            DateTime _CreateDate = Convert.ToDateTime(dsApplication.Tables[2].Rows[0]["CreatedDate"].ToString());
            if (ddlApplicationDay.Items.Count > 0)
                ddlApplicationDay.Items.Clear();
            ddlApplicationDay.Items.Add(new ListItem(_CreateDate.Day.ToString("00"), _CreateDate.Day.ToString("00")));
            if (ddlApplicationMonth.Items.Count > 0)
                ddlApplicationMonth.Items.Clear();
            ddlApplicationMonth.Items.Add(new ListItem(_CreateDate.Month.ToString("00"), _CreateDate.Month.ToString("00")));
            if (ddlApplicationYear.Items.Count > 0)
                ddlApplicationYear.Items.Clear();
            ddlApplicationYear.Items.Add(new ListItem(_CreateDate.Year.ToString("0000"), _CreateDate.Year.ToString("0000")));

            if (ddlNamedDriver.Text == "0")
            {
                rfvDriverFirst.Enabled = false;
                revDriverFirst.Enabled = false;
                rfvDriver1IDNo.Enabled = false;
                rfvDriver1LicenseNo.Enabled = false;
                rfvDriverTwo.Enabled = false;
                revDriverTwo.Enabled = false;
                rfvDriver2IDNo.Enabled = false;
                rfvDriver2LicenseNo.Enabled = false;
            }
            if (ddlNamedDriver.Text == "1")
            {
                rfvDriverFirst.Enabled = true;
                revDriverFirst.Enabled = true;
                rfvDriver1IDNo.Enabled = true;
                rfvDriver1LicenseNo.Enabled = true;
                rfvDriverTwo.Enabled = false;
                revDriverTwo.Enabled = false;
                rfvDriver2IDNo.Enabled = false;
                rfvDriver2LicenseNo.Enabled = false;
            }
            if (ddlNamedDriver.Text == "2")
            {
                rfvDriverFirst.Enabled = true;
                revDriverFirst.Enabled = true;
                rfvDriver1IDNo.Enabled = true;
                rfvDriver1LicenseNo.Enabled = true;
                rfvDriverTwo.Enabled = true;
                revDriverTwo.Enabled = true;
                rfvDriver2IDNo.Enabled = true;
                rfvDriver2LicenseNo.Enabled = true;
            }

            pnlCarDetails.Visible = true;

            // Renew Ext Com Date
            int intStartYear = dateTimeNow.Year - 1;
            int intEndYear = dateTimeNow.Year + 1;
            LoadDate(ddlExtComDay);
            ddlExtComDay.Items.Insert(0, new ListItem("", ""));
            LoadMonth(ddlExtComMonth);
            ddlExtComMonth.Items.Insert(0, new ListItem("", ""));
            LoadYear(ddlExtComYear, intStartYear, intEndYear);
            ddlExtComYear.Items.Insert(0, new ListItem("", ""));

            MyDatabase _myDb = new MyDatabase();
            string _strSelect = "SELECT CD.Dinfo2 "
                    + " FROM tblCarPolicy CP INNER JOIN tblCarDetailTH CD ON CD.CarId = CP.CECarId "
                    + " WHERE CP.RefCEUserId = " + txtUserId.Text.Trim() + " AND CP.CECarId= " + txtCarId.Text.Trim();
            object _extDate = _myDb.ExecuteScalarSqlStatement(_strSelect);
            if (_extDate != null && _extDate.ToString() != "")
            {
                chkExtComDate.Checked = true;
                ddlExtComDay.Style.Add("visibility", "visible");
                ddlExtComMonth.Style.Add("visibility", "visible");
                ddlExtComYear.Style.Add("visibility", "visible");
                DateTime extDate = Convert.ToDateTime(_extDate);

                ddlExtComDay.SelectedIndex = ddlExtComDay.Items.IndexOf(ddlExtComDay.Items.FindByValue(extDate.ToString("dd")));
                ddlExtComMonth.SelectedIndex = ddlExtComMonth.Items.IndexOf(ddlExtComMonth.Items.FindByValue(extDate.ToString("MM")));
                ddlExtComYear.SelectedIndex = ddlExtComYear.Items.IndexOf(ddlExtComYear.Items.FindByValue(extDate.ToString("yyyy")));
            }
            else
            {
                ddlExtComDay.Style.Add("visibility", "hidden");
                ddlExtComMonth.Style.Add("visibility", "hidden");
                ddlExtComYear.Style.Add("visibility", "hidden");
            }
            //*******************
            
            #endregion

        }
        else
        {
            lblSearchMessage.Text = Resources.General.CheckRefNo;
            divCar.Visible = false;
        }
        
    }

    public void LoadLastYearApplicationDetails()
    {
        if (lblLastYearRefNo.Text != string.Empty)
        {
            DataSet _dsLastYearApplication = new DataSet();
            NonGGPackageDB _nonggpackagedb = new NonGGPackageDB();
            _dsLastYearApplication = _nonggpackagedb.GetLastYearCarDetails(Convert.ToInt64(txtCarId.Text.Trim()), lblLastYearRefNo.Text.ToUpper());
            if (_dsLastYearApplication != null && _dsLastYearApplication.Tables.Count > 0 && _dsLastYearApplication.Tables[0].Rows.Count > 0)
            {
                txtCarModelYear.Text = _dsLastYearApplication.Tables[0].Rows[0]["CarYear"].ToString();
                txtCarMakeModel.Text = _dsLastYearApplication.Tables[0].Rows[0]["CarModel"].ToString();
                
                txtCurrentInsurer.Text = _dsLastYearApplication.Tables[0].Rows[0]["CompanyName"].ToString();

                txtEngineNumber.Text = _dsLastYearApplication.Tables[0].Rows[0]["EngineNumber"].ToString();
                txtChassisNumber.Text = _dsLastYearApplication.Tables[0].Rows[0]["ChassisNumber"].ToString();
                txtPlateNumber.Text = _dsLastYearApplication.Tables[0].Rows[0]["CarPlate"].ToString();
                txtRegistrationProvince.Text = _dsLastYearApplication.Tables[0].Rows[0]["CarPlateProvince"].ToString();
                ddlNCB.Text = _dsLastYearApplication.Tables[0].Rows[0]["NCB"].ToString();
               
                txtUserId.Text = _dsLastYearApplication.Tables[0].Rows[0]["RefCEUserId"].ToString();

                lblUpApplicantName.Text = _dsLastYearApplication.Tables[0].Rows[0]["Name"].ToString();
                lblUpPlanName.Text = _dsLastYearApplication.Tables[0].Rows[0]["Package"].ToString();
                txtCancelStatus.Text = "0";

                ddlCustomerType.Text = _dsLastYearApplication.Tables[0].Rows[0]["CustomerType"].ToString();
                txtCustomerName.Text = _dsLastYearApplication.Tables[0].Rows[0]["CustomerName"].ToString();
                txtPrefix.Text = _dsLastYearApplication.Tables[0].Rows[0]["Title"].ToString();
                txtBeneficiary.Text = _dsLastYearApplication.Tables[0].Rows[0]["Beneficiary"].ToString();
                txtInsuredPerson.Text = _dsLastYearApplication.Tables[0].Rows[0]["Name"].ToString();

                //txtContactNumber.Text = _dsLastYearApplication.Tables[0].Rows[0]["ContactNo"].ToString();
                MyDatabase _db = new MyDatabase();
                string _strSelect = "select C.Mobile "
                                    + "from tblCEUsrProfile P INNER JOIN tblOccupationInfo O ON P.Occupation = O.OccupationId "
                                    + "INNER JOIN tblCEContact C ON C.RefCEUserID = P.RefCEUserID INNER JOIN tblCEUser u ON u.CEID = C.RefCEUserID "
                                    + "Where P.RefCEUserId = " + txtUserId.Text;
                object _mobile = _db.ExecuteScalarSqlStatement(_strSelect);
                if (_mobile != null)
                {
                    txtContactNumber.Text = _mobile.ToString();
                }
                else
                {
                    txtContactNumber.Text = _dsLastYearApplication.Tables[0].Rows[0]["ContactNo"].ToString();
                }

                txtCurrentAddress.Text = _dsLastYearApplication.Tables[0].Rows[0]["PresentAddress"].ToString();
                txtSubDistrict.Text = _dsLastYearApplication.Tables[0].Rows[0]["SubDistrict"].ToString();
                txtStateProvince.Text = _dsLastYearApplication.Tables[0].Rows[0]["District"].ToString();
                txtProvince.Text = _dsLastYearApplication.Tables[0].Rows[0]["Province"].ToString();
                txtPostalCode.Text = _dsLastYearApplication.Tables[0].Rows[0]["PostalCode"].ToString();
                txtPackage.Text = _dsLastYearApplication.Tables[0].Rows[0]["Package"].ToString();

                if (_dsLastYearApplication.Tables[0].Rows[0]["IsMailingAddressDiff"] != DBNull.Value &&
                _dsLastYearApplication.Tables[0].Rows[0]["IsMailingAddressDiff"].ToString() == "True")
                {
                    //From CRM
                    trSameAddress1.Style.Add("display", "");
                    trSameAddress2.Style.Add("display", "");
                    trSameAddress3.Style.Add("display", "");
                    chkSameAddress.Checked = false;
                    txtSameAddress.Text = _dsLastYearApplication.Tables[0].Rows[0]["MailingAddress"].ToString();
                    txtSameAddrSubDistrict.Text = _dsLastYearApplication.Tables[0].Rows[0]["MailingSubDistrict"].ToString();
                    txtSameAddrStateProvince.Text = _dsLastYearApplication.Tables[0].Rows[0]["MailingDistrict"].ToString();
                    txtSameAddrProvince.Text = _dsLastYearApplication.Tables[0].Rows[0]["MailingProvince"].ToString();
                    txtSameAddrPostalCode.Text = _dsLastYearApplication.Tables[0].Rows[0]["MailingPostalCode"].ToString();
                    txtSameAddrName.Text = _dsLastYearApplication.Tables[0].Rows[0]["MailingName"].ToString();
                    refSameAddrName.Enabled = true;
                    refSameAddress.Enabled = true;
                    refSameAddrSubDistrict.Enabled = true;
                    refSameAddrStateProvince.Enabled = true;
                    refSameAddrProvince.Enabled = true;
                    refSameAddrPostalCode.Enabled = true;
                }
                else
                {
                    trSameAddress1.Style.Add("display", "none");
                    trSameAddress2.Style.Add("display", "none");
                    trSameAddress3.Style.Add("display", "none");
                    chkSameAddress.Checked = true;
                    txtSameAddress.Text = "";
                    txtSameAddrSubDistrict.Text = "";
                    txtSameAddrStateProvince.Text = "";
                    txtSameAddrProvince.Text = "";
                    txtSameAddrPostalCode.Text = "";
                    txtSameAddrName.Text = "";
                    refSameAddrName.Enabled = false;
                    refSameAddress.Enabled = false;
                    refSameAddrSubDistrict.Enabled = false;
                    refSameAddrStateProvince.Enabled = false;
                    refSameAddrProvince.Enabled = false;
                    refSameAddrPostalCode.Enabled = false;
                }

                if (_dsLastYearApplication.Tables[0].Rows[0]["Gender"] != DBNull.Value)
                {
                    ddlGender.Text = _dsLastYearApplication.Tables[0].Rows[0]["Gender"].ToString();
                }

                txtCitizenID.Text = "";
                if (_dsLastYearApplication.Tables[0].Rows[0]["IdentificationNo"] != DBNull.Value && _dsLastYearApplication.Tables[0].Rows[0]["IdentificationNo"].ToString() != string.Empty)
                {
                    txtCitizenID.Text = _dsLastYearApplication.Tables[0].Rows[0]["IdentificationNo"].ToString();
                }

                DateTime DOB = dateTimeNow;
                if (_dsLastYearApplication.Tables[0].Rows[0]["DOB"] != DBNull.Value && _dsLastYearApplication.Tables[0].Rows[0]["DOB"].ToString() != string.Empty)
                {
                    DOB = Convert.ToDateTime(_dsLastYearApplication.Tables[0].Rows[0]["DOB"].ToString());
                }
                AssignDate(DOB.Day, ddlDOBDay);
                AssignMonth(DOB.Month, ddlDOBMonth);
                AssignYear(DOB.Year, ddlDOBYear);
                DateTime DriverDOB1 = dateTimeNow.AddYears(-20);
                DateTime DriverDOB2 = dateTimeNow.AddYears(-20);
                ddlOccupation.Text = _dsLastYearApplication.Tables[0].Rows[0]["Occupation"].ToString();
                ddlNamedDriver.Text = _dsLastYearApplication.Tables[0].Rows[0]["NoOfDriver"].ToString();
                ddlNamedDriver_SelectedIndexChanged(null, null);
                txtDriverId1.Text = "0";
                txtDriverId2.Text = "0";
                if (_dsLastYearApplication.Tables.Count > 1 && ddlNamedDriver.Text != "0")
                {
                    if (_dsLastYearApplication.Tables[1].Rows.Count > 0 && _dsLastYearApplication.Tables[1].Rows[0]["DOB"] != DBNull.Value && _dsLastYearApplication.Tables[1].Rows[0]["DOB"].ToString() != string.Empty)
                    {
                        DriverDOB1 = Convert.ToDateTime(_dsLastYearApplication.Tables[1].Rows[0]["DOB"].ToString());
                    }
                    if (_dsLastYearApplication.Tables[1].Rows.Count > 1 && _dsLastYearApplication.Tables[1].Rows[1]["DOB"] != DBNull.Value && _dsLastYearApplication.Tables[1].Rows[1]["DOB"].ToString() != string.Empty)
                    {
                        DriverDOB2 = Convert.ToDateTime(_dsLastYearApplication.Tables[1].Rows[1]["DOB"].ToString());
                    }
                    if (_dsLastYearApplication.Tables[1].Rows.Count > 0)
                    {
                        txtDriverFirst.Text = _dsLastYearApplication.Tables[1].Rows[0]["FullName"].ToString();
                        txtDriver1IDNo.Text = _dsLastYearApplication.Tables[1].Rows[0]["IDNo"].ToString();
                        txtDriver1LicenseNo.Text = _dsLastYearApplication.Tables[1].Rows[0]["DrivingLicenseNumber"].ToString();
                    }
                    if (_dsLastYearApplication.Tables[1].Rows.Count > 1)
                    {
                        txtDriverTwo.Text = _dsLastYearApplication.Tables[1].Rows[1]["FullName"].ToString();
                        txtDriver2IDNo.Text = _dsLastYearApplication.Tables[1].Rows[1]["IDNo"].ToString();
                        txtDriver2LicenseNo.Text = _dsLastYearApplication.Tables[1].Rows[1]["DrivingLicenseNumber"].ToString();
                    }
                }
                AssignDate(DriverDOB1.Day, ddlDriver1DOBDay);
                AssignMonth(DriverDOB1.Month, ddlDriver1DOBMonth);
                AssignYear(DriverDOB1.Year, ddlDriver1DOBYear);
                AssignDate(DriverDOB2.Day, ddlDriver2DOBDay);
                AssignMonth(DriverDOB2.Month, ddlDriver2DOBMonth);
                AssignYear(DriverDOB2.Year, ddlDriver2DOBYear);

                DateTime _CreateDate = Convert.ToDateTime(_dsLastYearApplication.Tables[0].Rows[0]["CreatedDate"].ToString());
                if (ddlApplicationDay.Items.Count > 0)
                    ddlApplicationDay.Items.Clear();
                ddlApplicationDay.Items.Add(new ListItem(_CreateDate.Day.ToString("00"), _CreateDate.Day.ToString("00")));
                if (ddlApplicationMonth.Items.Count > 0)
                    ddlApplicationMonth.Items.Clear();
                ddlApplicationMonth.Items.Add(new ListItem(_CreateDate.Month.ToString("00"), _CreateDate.Month.ToString("00")));
                if (ddlApplicationYear.Items.Count > 0)
                    ddlApplicationYear.Items.Clear();
                ddlApplicationYear.Items.Add(new ListItem(_CreateDate.Year.ToString("0000"), _CreateDate.Year.ToString("0000")));

                if (ddlNamedDriver.Text == "0")
                {
                    rfvDriverFirst.Enabled = false;
                    revDriverFirst.Enabled = false;
                    rfvDriver1IDNo.Enabled = false;
                    rfvDriver1LicenseNo.Enabled = false;
                    rfvDriverTwo.Enabled = false;
                    revDriverTwo.Enabled = false;
                    rfvDriver2IDNo.Enabled = false;
                    rfvDriver2LicenseNo.Enabled = false;
                }
                if (ddlNamedDriver.Text == "1")
                {
                    rfvDriverFirst.Enabled = true;
                    revDriverFirst.Enabled = true;
                    rfvDriver1IDNo.Enabled = true;
                    rfvDriver1LicenseNo.Enabled = true;
                    rfvDriverTwo.Enabled = false;
                    revDriverTwo.Enabled = false;
                    rfvDriver2IDNo.Enabled = false;
                    rfvDriver2LicenseNo.Enabled = false;
                }
                if (ddlNamedDriver.Text == "2")
                {
                    rfvDriverFirst.Enabled = true;
                    revDriverFirst.Enabled = true;
                    rfvDriver1IDNo.Enabled = true;
                    rfvDriver1LicenseNo.Enabled = true;
                    rfvDriverTwo.Enabled = true;
                    revDriverTwo.Enabled = true;
                    rfvDriver2IDNo.Enabled = true;
                    rfvDriver2LicenseNo.Enabled = true;
                }
            }
        }
    }

    public void GetCarMoreDetails()
    {
        MyDatabase _db = new MyDatabase("GG_CRMDBConnectionString");
        string _spName = "sprocCXCRMNonGGCarMoreDetailSelectSingleItem";
        SortedList _spara = new SortedList();
        _spara.Add("@CECarId", Convert.ToInt64(txtCarId.Text.Trim()));
        _spara.Add("@RefCEUserId", Convert.ToInt64(txtUserId.Text));
        _spara.Add("@ProviderCompanyId", Convert.ToInt64(txtProviderId.Text));
        DataSet _dsCarMoreDetails = new DataSet();
        _dsCarMoreDetails = _db.GetDataSet(_spName, _spara);
        if (_dsCarMoreDetails != null && _dsCarMoreDetails.Tables.Count > 0 && _dsCarMoreDetails.Tables[1].Rows.Count > 0)
        {
            lblPRefNo.Text = _dsCarMoreDetails.Tables[1].Rows[0]["QuoteRefNo"].ToString();
            lblUpRefNo.Text = _dsCarMoreDetails.Tables[1].Rows[0]["QuoteRefNo"].ToString();
            lblUpApplicantName.Text = _dsCarMoreDetails.Tables[1].Rows[0]["Name"].ToString();
            lblUpInsurer.Text = _dsCarMoreDetails.Tables[1].Rows[0]["CompanyName"].ToString();
            lblUpPlanName.Text = _dsCarMoreDetails.Tables[1].Rows[0]["Package"].ToString();
            txtCancelStatus.Text = "0";
            if (_dsCarMoreDetails.Tables[0].Rows[0]["CancelStatus"] != DBNull.Value && _dsCarMoreDetails.Tables[0].Rows[0]["CancelStatus"].ToString() != "")
            {
                txtCancelStatus.Text = _dsCarMoreDetails.Tables[0].Rows[0]["CancelStatus"].ToString();
            }
            if (txtCancelStatus.Text == "1")
            {
                ddlOption.Items.Clear();
                ddlOption.Items.Add(new ListItem(Resources.CarInsurance.Select, "0"));
                ddlOption.Items.Add(new ListItem(Resources.CarInsurance.Retrieve, "RTRV"));
                ddlOption.SelectedIndex = 0;
            }
            else
            {
                LoadOption();
            }

            if (_dsCarMoreDetails.Tables.Count > 1 && _dsCarMoreDetails.Tables[1].Rows.Count > 0)
            {
                //lblUpPremium.Text = _dsCarMoreDetails.Tables[1].Rows[0]["TotalCollectedPremiumWOD"].ToString();
                lblUpPremium.Text = _dsCarMoreDetails.Tables[1].Rows[0]["TotalCollectedPremium"].ToString();
                

                lblUpPremiumWD.Text = _dsCarMoreDetails.Tables[1].Rows[0]["TotalCollectedPremiumWD"].ToString();
                lblUpPremiumWOD.Text = _dsCarMoreDetails.Tables[1].Rows[0]["TotalCollectedPremiumWOD"].ToString();
                lblUpPaymentType.Text = _dsCarMoreDetails.Tables[1].Rows[0]["PaymentType"].ToString();
                lblUpPaymentStatus.Text = _dsCarMoreDetails.Tables[1].Rows[0]["PaymentStatus"].ToString();

                txtWDPremium.Text = _dsCarMoreDetails.Tables[1].Rows[0]["TotalCollectedPremiumWD"].ToString();
                txtWODPremium.Text = _dsCarMoreDetails.Tables[1].Rows[0]["TotalCollectedPremiumWOD"].ToString();
                if (txtIsWD.Text != string.Empty && txtIsWD.Text == "0")
                {
                    txtAgentPrice.Text = txtWODPremium.Text;
                }
                else
                {
                    txtAgentPrice.Text = txtWDPremium.Text;
                }
                if (_dsCarMoreDetails.Tables[1].Rows[0]["OriginalPremiumWD"] != DBNull.Value &&
                    _dsCarMoreDetails.Tables[1].Rows[0]["OriginalPremiumWD"].ToString() != string.Empty)
                {
                    decimal _dOriginalPremiumWD = 0;
                    if (!decimal.TryParse(_dsCarMoreDetails.Tables[1].Rows[0]["OriginalPremiumWD"].ToString(), out _dOriginalPremiumWD))
                    {
                        _dOriginalPremiumWD = 0;
                    }
                    txtOriginalPriceWD.Text = _dOriginalPremiumWD.ToString("#0.00");
                }
                if (_dsCarMoreDetails.Tables[1].Rows[0]["OriginalPremiumWOD"] != DBNull.Value &&
                    _dsCarMoreDetails.Tables[1].Rows[0]["OriginalPremiumWOD"].ToString() != string.Empty)
                {
                    decimal _dOriginalPremiumWOD = 0;
                    if (!decimal.TryParse(_dsCarMoreDetails.Tables[1].Rows[0]["OriginalPremiumWOD"].ToString(), out _dOriginalPremiumWOD))
                    {
                        _dOriginalPremiumWOD = 0;
                    }
                    txtOriginalPriceWOD.Text = _dOriginalPremiumWOD.ToString("#0.00");
                }
                if (_dsCarMoreDetails.Tables[1].Rows[0]["ApprovedPremium"] != DBNull.Value &&
                    _dsCarMoreDetails.Tables[1].Rows[0]["ApprovedPremium"].ToString() != string.Empty)
                {
                    decimal _dApprovedPremium = 0;
                    if (!decimal.TryParse(_dsCarMoreDetails.Tables[1].Rows[0]["ApprovedPremium"].ToString(), out _dApprovedPremium))
                    {
                        _dApprovedPremium = 0;
                    }
                   
                }
            }
            if (ddlOption.Items.Count > 0)
            {
                ddlOption_SelectedIndexChanged(null, null);
            }
        }
        else
        {
            DataSet _dsCarDetails = new DataSet();
            _dsCarDetails = GetBrokerPremium();
            if (_dsCarDetails != null && _dsCarDetails.Tables.Count > 0 && _dsCarDetails.Tables[0].Rows.Count > 0)
            {
                lblPaymentMode.Text = "";
                if (_dsCarDetails.Tables[0].Rows[0]["PaymentMode"] != DBNull.Value)
                {
                    if (_dsCarDetails.Tables[0].Rows[0]["PaymentMode"].ToString() == "CR")
                        lblPaymentMode.Text = "Credit Card";
                    else if (_dsCarDetails.Tables[0].Rows[0]["PaymentMode"].ToString() == "TR")
                        lblPaymentMode.Text = "โอนเงิน";
                }

                txtAgentComments.Text = "";
                if (_dsCarDetails.Tables[0].Rows[0]["Info8"] != DBNull.Value && _dsCarDetails.Tables[0].Rows[0]["Info8"].ToString() != string.Empty)
                {
                    txtAgentComments.Text = _dsCarDetails.Tables[0].Rows[0]["Info8"].ToString();
                }
                pnlDetails.Visible = true;
                lblPRefNo.Text = _dsCarDetails.Tables[0].Rows[0]["Info1"].ToString();
                lblUpRefNo.Text = _dsCarDetails.Tables[0].Rows[0]["Info1"].ToString();
                if (_dsCarDetails.Tables[0].Rows[0]["Info4"] != DBNull.Value && _dsCarDetails.Tables[0].Rows[0]["Info4"].ToString() == "1")
                {
                    lblCompanyStaff.Text = "1";
                    if (Session[General.UserRole].ToString() == "100")
                    {
                        lblOptionError.Text = Resources.Proposal.AccessDenied;
                        btnSubmit.Enabled = false;
                    }
                }
                else
                {
                    lblCompanyStaff.Text = "0";
                }

                lblUpInsurer.Text = CE.Global.General.GetProviderName(Convert.ToInt64(txtProviderId.Text), lblLangOption.Text);
                lblUpPlanName.Text = _dsCarDetails.Tables[0].Rows[0]["Package"].ToString();
                lblUpPremiumWD.Text = _dsCarDetails.Tables[0].Rows[0]["PremiumAmountWD"].ToString();
                lblUpPremiumWOD.Text = _dsCarDetails.Tables[0].Rows[0]["PremiumAmountWOD"].ToString();

                //lblUpPremium.Text = _dsCarDetails.Tables[0].Rows[0]["PremiumAmountWOD"].ToString();
                lblUpPremium.Text = _dsCarDetails.Tables[0].Rows[0]["PremiumAmount"].ToString();
             
                txtWDPremium.Text = _dsCarDetails.Tables[0].Rows[0]["PremiumAmountWD"].ToString();
                txtAFTPremiumWOD.Text = _dsCarDetails.Tables[0].Rows[0]["PremiumTescoCashWOD"].ToString();
                txtAFTPremiumWD.Text = _dsCarDetails.Tables[0].Rows[0]["PremiumTescoCashWD"].ToString();
                txtWODPremium.Text = _dsCarDetails.Tables[0].Rows[0]["PremiumAmountWOD"].ToString();
                if (txtIsWD.Text != string.Empty && txtIsWD.Text == "0")
                {
                    txtAgentPrice.Text = _dsCarDetails.Tables[0].Rows[0]["PremiumAmountWOD"].ToString();
                }
                else
                {
                    txtAgentPrice.Text = _dsCarDetails.Tables[0].Rows[0]["PremiumAmountWD"].ToString();
                }
                if (_dsCarDetails.Tables[0].Rows[0]["OriginalPremiumWD"] != DBNull.Value &&
                    _dsCarDetails.Tables[0].Rows[0]["OriginalPremiumWD"].ToString() != string.Empty)
                {
                    decimal _dOriginalPremiumWD = 0;
                    if (!decimal.TryParse(_dsCarDetails.Tables[0].Rows[0]["OriginalPremiumWD"].ToString(), out _dOriginalPremiumWD))
                    {
                        _dOriginalPremiumWD = 0;
                    }
                    txtOriginalPriceWD.Text = _dOriginalPremiumWD.ToString("#0.00");
                }
                if (_dsCarDetails.Tables[0].Rows[0]["OriginalPremiumWOD"] != DBNull.Value &&
                    _dsCarDetails.Tables[0].Rows[0]["OriginalPremiumWOD"].ToString() != string.Empty)
                {
                    decimal _dOriginalPremiumWOD = 0;
                    if (!decimal.TryParse(_dsCarDetails.Tables[0].Rows[0]["OriginalPremiumWOD"].ToString(), out _dOriginalPremiumWOD))
                    {
                        _dOriginalPremiumWOD = 0;
                    }
                    txtOriginalPriceWOD.Text = _dOriginalPremiumWOD.ToString("#0.00");
                }
                if (_dsCarDetails.Tables[0].Rows[0]["ApprovedPremium"] != DBNull.Value &&
                    _dsCarDetails.Tables[0].Rows[0]["ApprovedPremium"].ToString() != string.Empty)
                {
                    decimal _dApprovedPremium = 0;
                    if (!decimal.TryParse(_dsCarDetails.Tables[0].Rows[0]["ApprovedPremium"].ToString(), out _dApprovedPremium))
                    {
                        _dApprovedPremium = 0;
                    }
                }

                lblUpPaymentStatus.Text = "PENDING";
                if (_dsCarDetails != null && _dsCarDetails.Tables.Count > 1 && _dsCarDetails.Tables[1].Rows.Count > 0)
                {
                    lblUpPaymentStatus.Text = "PENDING";
                }
            }
        }

        if (_dsCarMoreDetails != null && _dsCarMoreDetails.Tables.Count > 0 && _dsCarMoreDetails.Tables[0].Rows.Count > 0)
        {
            if (_dsCarMoreDetails.Tables[0].Rows[0]["Mailing"] != DBNull.Value && _dsCarMoreDetails.Tables[0].Rows[0]["Mailing"].ToString() != string.Empty)
            {
                if (_dsCarMoreDetails.Tables[0].Rows[0]["Mailing"].ToString() == "1")
                {
                    ddlOption.Items.Clear();
                    ddlOption.Items.Add(new ListItem(Resources.CarInsurance.Select, "0"));
                    //YUI@15-08-2014 only agent can't edit.
                    if (Session[CE.Global.General.UserRole].ToString() != "100")
                    {
                        ddlOption.Items.Add(new ListItem(Resources.CarInsurance.MoreDetails, "EDIT"));
                        btnSubmit.Enabled = false;
                        btnReference.Visible = true;
                    }
                    ddlOption.Items.Add(new ListItem(Resources.CarInsurance.UploadFile, "UPLD"));
                    ddlOption.SelectedIndex = 0;
                }
            }
        }
    }

    public DataSet GetBrokerPremium()
    {
        MyDatabase _db = new MyDatabase("GG_CRMDBConnectionString");
        SortedList _sPara = new SortedList();
        string _spName = "sprocCXCRMBrokerPremiumSelectSingleItem";
        _sPara.Add("@CXBrokerProviderId", Convert.ToInt64(txtProviderId.Text));
        _sPara.Add("@CECarId", Convert.ToInt64(txtCarId.Text.Trim()));
        _sPara.Add("@SelectedStatus", true);
        DataSet _ds = new DataSet();
        return _ds = _db.GetDataSet(_spName, _sPara);
        
    }

    public DataSet GetPaymentAmounts()
    {
        MyDatabase _db = new MyDatabase("GG_CRMDBConnectionString");
        SortedList _sPara = new SortedList();
        string _spName = "sprocCXCRMPaymentsAmountsSelectItembyQuoteRefNo";
        _sPara.Add("@QuoteRefNo", lblUpRefNo.Text);
        DataSet _ds = new DataSet();
        return _ds = _db.GetDataSet(_spName, _sPara);
        
    }

    public DataSet GetApprovedPayments()
    {
        MyDatabase _db = new MyDatabase("GG_CRMDBConnectionString");
        SortedList _sPara = new SortedList();
        string _spName = "sprocCXCRMApprovedPaymentSelectItemList";
        _sPara.Add("@ProviderCompanyId", Convert.ToInt64(txtProviderId.Text));
        _sPara.Add("@CECarId", Convert.ToInt64(txtCarId.Text.Trim()));
        DataSet _ds = new DataSet();
        return _ds = _db.GetDataSet(_spName, _sPara);
       
    }

    public bool CheckSelectedItem(string QouteRefNo)
    {
        bool _Result = false;
        MyDatabase _db = new MyDatabase("GG_CRMDBConnectionString");
        SortedList _sPara = new SortedList();
        string _spName = "sprocCXCRMNonGGPremiumSelectItemByQuoteRefNo";
        _sPara.Add("@QouteRefNo", QouteRefNo);
        DataSet _ds = new DataSet();
        _ds = _db.GetDataSet(_spName, _sPara);
        if (_ds != null && _ds.Tables.Count > 0 && _ds.Tables[0].Rows.Count > 0)
        {
            _Result = true;
        }
        return _Result;
    }

    public bool CheckApplicationProcessStatus(string QouteRefNo, string Process)
    {
        bool _Result = true;
        MyDatabase _db = new MyDatabase("GG_CRMDBConnectionString");
        SortedList _sPara = new SortedList();
        string _spName = "SELECT Mailing FROM tblNonGGCarMoreDetails WHERE [QuoteRefNo] = @QuoteRefNo AND [Status] = 1";
        _sPara.Add("@QuoteRefNo", QouteRefNo);
        DataTable _dt = new DataTable();
        _dt = _db.GetDataTable(_spName, _sPara);
        if (_dt != null && _dt.Rows.Count > 0)
        {
            string _status = "";
            if (Process.ToUpper() == "MAILING")
            {
                if (_dt.Rows[0]["Mailing"].ToString() != null && _dt.Rows[0]["Mailing"].ToString() != string.Empty)
                {
                    _status = _dt.Rows[0]["Mailing"].ToString();
                    if (_status != string.Empty && _status == "1")
                    {
                        _Result = false;
                    }
                }
            }
        }
        return _Result;
    }

    private bool GetBoolean(Int16 val)
    {
        bool _result = false;
        if (val == 1)
        {
            _result = true;
        }
        return _result;
    }

    private void AssignDate(Int32 _date, DropDownList ddl)
    {
        string val = _date.ToString();
        if (_date < 10)
        {
            val = "0" + _date.ToString();
        }
       
        ddl.Text = val;
    }

    private void AssignMonth(Int32 _month, DropDownList ddl)
    {
        string val = "00";
        string monthname = Resources.General.Select;
        if (_month < 10)
        {
            val = "0" + _month.ToString();
        }
        else
        {
            val = _month.ToString();
        }
      
        ddl.Text = val;
    }

    private void AssignYear(Int32 _year, DropDownList ddl)
    {
        if (_year > (dateTimeNow.Year + 400))
        {
            _year = _year - 543;
        }
        string val = _year.ToString();
     
        ddl.Text = val;
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        Page.Validate("nongg");

        if (lblCompanyStaff.Text == "1" && Session[General.UserRole].ToString() == "100")
        {
            lblOptionError.Text = Resources.Proposal.AccessDenied;
            return;
        }

        if (Page.IsValid)
        {
            MyDatabase _dbIsNew = new MyDatabase();
            string strIsNew = "SELECT CECarId FROM [tblNonGGCarMoreDetails] WHERE CECarId = @CECarId And RefCEUserId = @RefCEUserId";
            SortedList _paraIsNewList = new SortedList();
            _paraIsNewList.Add("@CECarId", txtCarId.Text);
            _paraIsNewList.Add("@RefCEUserId", txtUserId.Text);
            object _retVal = _dbIsNew.ExecuteScalarSqlStatement(strIsNew, _paraIsNewList);
            Int64 _CarId = 0;

            if (_retVal != null)
            {
                if (!Int64.TryParse(_retVal.ToString(), out _CarId))
                    _CarId = 0;
            }

            DateTime _dtCommDate = new DateTime(Convert.ToInt32(ddlCommenceYear.Text), Convert.ToInt32(ddlCommenceMonth.Text), Convert.ToInt32(ddlCommenceDay.Text));
            if (_CarId == 0)
            {
                if (_dtCommDate.Date < dateTimeNow.Date)
                {
                    lblOptionError.Text = Resources.Proposal.PolicyStartDate_Voluntary + " ต้องมากกว่าวันที่ปัจจุบัน";
                    return;
                }
            }

            DateTime? dteExtCommDate = null;
            if (chkExtComDate.Checked)
            {
                if (chkExtComDate.Checked &&
                    ddlExtComYear.SelectedIndex > 0 && ddlExtComMonth.SelectedIndex > 0 && ddlExtComDay.SelectedIndex > 0)
                {
                    DateTime _dtExtCommDate = new DateTime(Convert.ToInt32(ddlExtComYear.Text), Convert.ToInt32(ddlExtComMonth.Text), Convert.ToInt32(ddlExtComDay.Text));

                    if (_CarId == 0)
                    {
                        if (_dtExtCommDate.Date < _dtCommDate.Date)
                        {
                            lblOptionError.Text = "ขยายวันที่คุ้มครอง ต้องมากกว่า " + Resources.Proposal.PolicyStartDate_Voluntary;
                            return;
                        }
                    }

                    dteExtCommDate = _dtExtCommDate;
                }
            }

            lblLoadMessage.Text = string.Empty;
            Int64 _result = -1;
            Int64 _AgentId = 0;
            Int64 _AdminId = 0;
            if (!Int64.TryParse(lblAgentId.Text, out _AgentId))
            {
                _AgentId = 0;
            }
            if (!Int64.TryParse(lblAdminId.Text, out _AdminId))
            {
                _AdminId = 0;
            }
            txtLastQuoteRefNo.Text = txtSearch.Text.Trim();
            NonGGPackage _nonggpackage = new NonGGPackage();
            NonGGPackageDB _nonggpackagedb = new NonGGPackageDB();
            _nonggpackage.CECarId = Convert.ToInt64(txtCarId.Text);
            _nonggpackage.ProviderCompanyId = Convert.ToInt64(txtProviderId.Text);
            _nonggpackage.Title = Server.HtmlEncode(txtPrefix.Text);
            _nonggpackage.CustomerType = ddlCustomerType.Text;
            _nonggpackage.CustomerName = Server.HtmlEncode(txtCustomerName.Text);
            _nonggpackage.Name = Server.HtmlEncode(txtInsuredPerson.Text);
            DateTime _dtDOB = new DateTime(Convert.ToInt32(ddlDOBYear.Text), Convert.ToInt32(ddlDOBMonth.Text), Convert.ToInt32(ddlDOBDay.Text));
            _nonggpackage.DOB = _dtDOB;
            _nonggpackage.Gender = ddlGender.Text;
            _nonggpackage.Occupation = Convert.ToInt32(ddlOccupation.Text);
            _nonggpackage.ContactNo = Server.HtmlEncode(txtContactNumber.Text);
            _nonggpackage.OfficePhoneNo = Server.HtmlEncode(txtOtherContactNumber.Text);
            _nonggpackage.IdentificationNo = Server.HtmlEncode(txtCitizenID.Text);
            _nonggpackage.PresentAddress = Server.HtmlEncode(txtCurrentAddress.Text);
            _nonggpackage.SubDistrict = Server.HtmlEncode(txtSubDistrict.Text);
            _nonggpackage.District = Server.HtmlEncode(txtStateProvince.Text);
            _nonggpackage.Province = Server.HtmlEncode(txtProvince.Text);
            _nonggpackage.PostalCode = txtPostalCode.Text;

            _nonggpackage.IsMailingAddress = !chkSameAddress.Checked;
            if (!chkSameAddress.Checked)
            {
                _nonggpackage.MailingAddress = Server.HtmlEncode(txtSameAddress.Text);
                _nonggpackage.MailingSubDistrict = Server.HtmlEncode(txtSameAddrSubDistrict.Text);
                _nonggpackage.MailingDistrict = Server.HtmlEncode(txtSameAddrStateProvince.Text);
                _nonggpackage.MailingProvince = Server.HtmlEncode(txtSameAddrProvince.Text);
                _nonggpackage.MailingPostalCode = txtSameAddrPostalCode.Text;
                _nonggpackage.MailingName = txtSameAddrName.Text;
            }
            else
            {
                txtSameAddress.Text = "";
                txtSameAddrSubDistrict.Text = "";
                txtSameAddrStateProvince.Text = "";
                txtSameAddrProvince.Text = "";
                txtSameAddrPostalCode.Text = "";
                txtSameAddrName.Text = "";
            }

            _nonggpackage.Package = Server.HtmlEncode(txtPackage.Text);
            _nonggpackage.NoOfDriver = Convert.ToInt16(ddlNamedDriver.Text);
            _nonggpackage.InsuranceType = Convert.ToInt32(ddlInsuranceType.Text);
            //Yui@22/01/2015
            if (chkMile.Checked)
                _nonggpackage.Mile = 1;
            else
                _nonggpackage.Mile = 0;
            //End
            _nonggpackage.GarageType = Convert.ToInt32(ddlGarageType.Text);
            _nonggpackage.CarYear = Convert.ToInt32(txtCarModelYear.Text);
            _nonggpackage.CarModel = Server.HtmlEncode(txtCarMakeModel.Text);
          
            _nonggpackage.Beneficiary = Server.HtmlEncode(txtBeneficiary.Text);
            _nonggpackage.VehicleType = Convert.ToInt32(ddlVehicleType.Text);
          
            Int32 _outSumInsurred = 0;
            if (!Int32.TryParse(txtSumInsured.Text, out _outSumInsurred))
            {
                _outSumInsurred = 0;
            }
            _nonggpackage.SumInsured = _outSumInsurred;
            _nonggpackage.NCB = Convert.ToInt32(ddlNCB.Text);
            _nonggpackage.CurrentInsurer = Server.HtmlEncode(txtCurrentInsurer.Text);
            _nonggpackage.CarPlate = Server.HtmlEncode(txtPlateNumber.Text);
            _nonggpackage.CarPlateProvince = Server.HtmlEncode(txtRegistrationProvince.Text);
            _nonggpackage.EngineNumber = Server.HtmlEncode(txtEngineNumber.Text);
            _nonggpackage.ChassisNumber = Server.HtmlEncode(txtChassisNumber.Text);
          
            
            _nonggpackage.CoverageStart = _dtCommDate;
            DateTime _dtPolicyDate = new DateTime(Convert.ToInt32(ddlPolicyYear.Text), Convert.ToInt32(ddlPolicyMonth.Text), Convert.ToInt32(ddlPolicyDay.Text));
            _nonggpackage.CTPLStart = _dtPolicyDate;

            _nonggpackage.Premium = Convert.ToSingle(txtInsurancePremium.Text);
            _nonggpackage.IsCTPL = GetBoolean(Convert.ToInt16(ddlCTPL.Text));
            _nonggpackage.CTPL = Convert.ToSingle(txtCTPL.Text);

            _nonggpackage.TotalCollectedPremium = Convert.ToSingle(txtCollectedAmount.Text);
            _nonggpackage.TotalPremium = Convert.ToSingle(txtTotalPremium.Text);
            _nonggpackage.TermPremium = Convert.ToSingle(txtTotalPremium.Text);
          
            _nonggpackage.QuoteRefNo = txtNewQuoteRefNo.Text;
            _nonggpackage.Status = true;
            _nonggpackage.RefCEUserId = Convert.ToInt64(txtUserId.Text);
            if (Session[CE.Global.General.UserRole] != null && Session[CE.Global.General.UserRole].ToString() == "100")
            {
                _nonggpackage.AgentId = Convert.ToInt64(Session[CE.Global.General.UserId].ToString());
                _nonggpackage.AdminId = _AdminId;
            }
            else
            {
                if (_AgentId == 0)
                {
                    _nonggpackage.AgentId = Convert.ToInt64(Session[CE.Global.General.UserId].ToString());
                }
                else
                {
                    _nonggpackage.AgentId = _AgentId;
                }

                _nonggpackage.AdminId = Convert.ToInt64(Session[CE.Global.General.UserId].ToString());
            }
            _nonggpackage.Info1 = ddlApplicationType.Text;
            if (ddlApplicationType.Text == "REN" || ddlApplicationType.Text == "CHB")
            {
                _nonggpackage.Info2 = txtLastYearPolicyNo.Text.Trim();
            }
            if (_nonggpackage.ProviderCompanyId == 43)
            {
                _nonggpackage.Info3 = txtInsurerEmail.Text.Trim();
            }
            if (chkIsCreditCardOwner.Checked)
            {
                _nonggpackage.IsCreditCardOwner = 1;
            }
            if (chkPromotion.Checked)
            {
                _nonggpackage.PromotionCode = "1";
            }
            if (trModificationAmount.Visible == true)
            {
                _nonggpackage.Info4 = Server.HtmlEncode(txtModificationAmount.Text.Trim());
            }
            _nonggpackage.Info8 = Server.HtmlEncode(txtAgentRemarkDetails.Text);
            _result = _nonggpackagedb.Insert(_nonggpackage);
            
            Int32 driverresult = 0;
            if (_result > 0)
            {
                MyDatabase _db = new MyDatabase();
                string strUpdate = "Update tblCEContact SET OtherContact2 = @OtherContact2 Where RefCEUserID = @CustomerID";
                SortedList _paraList = new SortedList();
                _paraList.Add("@OtherContact2", Server.HtmlEncode(txtOtherContactNumber.Text.Trim()));
                _paraList.Add("@CustomerID", txtUserId.Text);
                int _retValue = _db.ExecuteNonSqlStatement(strUpdate, _paraList);

                // Renew Ext Com Date
                string _strUpdateSQL = "UPDATE tblCarDetailTH SET ";
                if (dteExtCommDate != null)
                {
                    _strUpdateSQL += " Dinfo2 = '" + dteExtCommDate.Value.ToString("yyyy-MM-dd") + "' ";
                }
                else
                {
                    _strUpdateSQL += " Dinfo2 = NULL ";
                }
                _strUpdateSQL += " WHERE CarID = " + txtCarId.Text + " AND RefCEUserID = " + txtUserId.Text;
                _retValue = _db.ExecuteNonSqlStatement(_strUpdateSQL);
                //*******************

                if (Convert.ToInt16(ddlNamedDriver.Text) > 0)
                {
                    if (SaveDriverDetails())
                    {
                        driverresult = 1;
                        pnlCarDetails.Visible = false;
                        lblOptionMessage.Text = Resources.CarInsurance.SuccessfullySaved;
                        pnlOptionMessage.Visible = true;
                        pnlDetails.Visible = true;
                        divCar.Visible = true;
                    }
                    else
                    {
                        driverresult = 0;
                    }
                }
                else
                {
                    driverresult = 1;
                }

                if (driverresult > 0)
                {
                    string _fileName = lblUpRefNo.Text.Trim() + "_" + dateTimeNow.Day.ToString("00") + "-" + dateTimeNow.Month.ToString("00") + "-" + dateTimeNow.Year;
                    string _filePath = GetExcelFilePath(Convert.ToInt64(txtProviderId.Text.Trim()), lblUpRefNo.Text.Trim());
                    string ExcelFile = GenerateNonGGExcel(_nonggpackage.CECarId, _nonggpackage.ProviderCompanyId, _filePath, _fileName);
                    if (ExcelFile != null)
                    {
                        Int64 _excelResult = -1;
                        _excelResult = _nonggpackagedb.UpdateExcelName(_nonggpackage.CECarId, ExcelFile);
                        if (_excelResult > 0)
                        {
                            string mailBody = "";
                            string _emailTitle = "";
                            string _toemail = "";
                            string _ccemail = "";
                            string _bccemail = "";
                            _emailTitle = "[" + lblUpRefNo.Text + "] ส่งงานประกันรถ คุณ [" + _nonggpackage.Name + "] [" + _nonggpackage.CarPlate + "]";
                            if (ddlApplicationType.Text == "NEW")
                            {
                                mailBody += Resources.Proposal.ApplicationType + " : " + Resources.Proposal.AppTypeNew + "<br/><br/>";
                            }
                            else if (ddlApplicationType.Text == "REN")
                            {
                                mailBody += Resources.Proposal.ApplicationType + " : " + Resources.Proposal.AppTypeRenewalSameInsurer + "<br/><br/>";
                            }
                            else if (ddlApplicationType.Text == "RNO")
                            {
                                mailBody += Resources.Proposal.ApplicationType + " : " + Resources.Proposal.AppTypeRenewalOtherInsurer + "<br/><br/>";
                            }
                            else if (ddlApplicationType.Text == "CHB")
                            {
                                mailBody += Resources.Proposal.ApplicationType + " : " + Resources.Proposal.AppTypeChangeBroker + "<br/><br/>";
                            }
                            mailBody += Resources.General.CustomerName + " : " + _nonggpackage.Name + "<br/><br/>";
                            mailBody += Resources.General.InsuranceCompany + " : " + txtInsuranceCompany.Text.Trim() + "<br/><br/>";
                            mailBody += Resources.General.InsuranceType + " : " + ddlInsuranceType.SelectedItem.Text + "<br/><br/>";
                            mailBody += Resources.NonGG.GarageType + " : " + ddlGarageType.SelectedItem.Text + "<br/><br/>";
                            mailBody += Resources.General.TotalCollectedAmount + " : " + txtCollectedAmount.Text.Trim() + "<br/><br/>";
                            string URL = ConfigurationManager.AppSettings["TH.BKKPaymentPage"].ToString(); //http://www.gluaygluay.com/payment/
                            mailBody += Resources.General.PaymentLink + " : " + URL + "?ref=" + lblUpRefNo.Text.Trim() + "<br/><br/>";
                            mailBody += Resources.General.Broker + " : " + Session[CE.Global.General.UserName].ToString() + "<br/><br/>";
                            _toemail = CE.Configuration.MyConfigurationManager.GetAppSettingValue("ADMIN");
                            
                            _ccemail = "";//Session[CE.Global.General.UserEmail].ToString();
                            _bccemail = "";
                            if (Session[General.UserRole].ToString() == "100")
                            {
                                _ccemail += Session[General.SMTPReplyTo].ToString();
                            }

                            bool _mailSendingStatus = false;
                           _mailSendingStatus = MyMailManager.SendGGMail(ConfigurationManager.AppSettings["GGFormsSMTPAccount"].ToString(), ConfigurationManager.AppSettings["GGFormsSMTPAuthCode"].ToString(), _toemail, _ccemail, _bccemail, _emailTitle, mailBody, Session[General.SMTPReplyTo].ToString());

                            pnlCarDetails.Visible = false;
                            lblOptionMessage.Text = Resources.CarInsurance.SuccessfullySaved;
                            pnlOptionMessage.Visible = true;
                            divCar.Visible = true;

                            if (!_mailSendingStatus)
                            {
                                lblOptionMessage.Text += ". Email notification was FAILED.";
                            }
                            ddlOption.SelectedIndex = 0;
                            ddlOption_SelectedIndexChanged(null, null);

                        }
                    }
                }
            }
        }
        else
        {
            lblOptionError.Text = Resources.CarInsurance.SuccessfullySaved;
            pnlOptionMessage.Visible = true;
        }
    }

    protected void btnReference_Click(object sender, EventArgs e)
    {
        Page.Validate("nongg");

        if (lblCompanyStaff.Text == "1" && Session[General.UserRole].ToString() == "100")
        {
            lblOptionError.Text = Resources.Proposal.AccessDenied;
            return;
        }

        if (Page.IsValid)
        {
            MyDatabase _dbIsNew = new MyDatabase();
            string strIsNew = "SELECT CECarId FROM [tblNonGGCarMoreDetails] WHERE CECarId = @CECarId And RefCEUserId = @RefCEUserId";
            SortedList _paraIsNewList = new SortedList();
            _paraIsNewList.Add("@CECarId", txtCarId.Text);
            _paraIsNewList.Add("@RefCEUserId", txtUserId.Text);
            object _retVal = _dbIsNew.ExecuteScalarSqlStatement(strIsNew, _paraIsNewList);
            Int64 _CarId = 0;

            if (_retVal != null)
            {
                if (!Int64.TryParse(_retVal.ToString(), out _CarId))
                    _CarId = 0;
            }

            DateTime _dtCommDate = new DateTime(Convert.ToInt32(ddlCommenceYear.Text), Convert.ToInt32(ddlCommenceMonth.Text), Convert.ToInt32(ddlCommenceDay.Text));
            
            DateTime? dteExtCommDate = null;
            if (chkExtComDate.Checked)
            {
                if (chkExtComDate.Checked &&
                    ddlExtComYear.SelectedIndex > 0 && ddlExtComMonth.SelectedIndex > 0 && ddlExtComDay.SelectedIndex > 0)
                {
                    DateTime _dtExtCommDate = new DateTime(Convert.ToInt32(ddlExtComYear.Text), Convert.ToInt32(ddlExtComMonth.Text), Convert.ToInt32(ddlExtComDay.Text));
                    dteExtCommDate = _dtExtCommDate;
                }
            }

            lblLoadMessage.Text = string.Empty;
            Int64 _result = -1;
            Int64 _AgentId = 0;
            Int64 _AdminId = 0;
            if (!Int64.TryParse(lblAgentId.Text, out _AgentId))
            {
                _AgentId = 0;
            }
            if (!Int64.TryParse(lblAdminId.Text, out _AdminId))
            {
                _AdminId = 0;
            }
            txtLastQuoteRefNo.Text = txtSearch.Text.Trim();
            NonGGPackage _nonggpackage = new NonGGPackage();
            NonGGPackageDB _nonggpackagedb = new NonGGPackageDB();
            _nonggpackage.CECarId = Convert.ToInt64(txtCarId.Text);
            _nonggpackage.ProviderCompanyId = Convert.ToInt64(txtProviderId.Text);
            _nonggpackage.Title = Server.HtmlEncode(txtPrefix.Text);
            _nonggpackage.CustomerType = ddlCustomerType.Text;
            _nonggpackage.CustomerName = Server.HtmlEncode(txtCustomerName.Text);
            _nonggpackage.Name = Server.HtmlEncode(txtInsuredPerson.Text);
            DateTime _dtDOB = new DateTime(Convert.ToInt32(ddlDOBYear.Text), Convert.ToInt32(ddlDOBMonth.Text), Convert.ToInt32(ddlDOBDay.Text));
            _nonggpackage.DOB = _dtDOB;
            _nonggpackage.Gender = ddlGender.Text;
            _nonggpackage.Occupation = Convert.ToInt32(ddlOccupation.Text);
            _nonggpackage.ContactNo = Server.HtmlEncode(txtContactNumber.Text);
            _nonggpackage.OfficePhoneNo = Server.HtmlEncode(txtOtherContactNumber.Text);
            _nonggpackage.IdentificationNo = Server.HtmlEncode(txtCitizenID.Text);
            _nonggpackage.PresentAddress = Server.HtmlEncode(txtCurrentAddress.Text);
            _nonggpackage.SubDistrict = Server.HtmlEncode(txtSubDistrict.Text);
            _nonggpackage.District = Server.HtmlEncode(txtStateProvince.Text);
            _nonggpackage.Province = Server.HtmlEncode(txtProvince.Text);
            _nonggpackage.PostalCode = txtPostalCode.Text;

            _nonggpackage.IsMailingAddress = !chkSameAddress.Checked;
            if (!chkSameAddress.Checked)
            {
                _nonggpackage.MailingAddress = Server.HtmlEncode(txtSameAddress.Text);
                _nonggpackage.MailingSubDistrict = Server.HtmlEncode(txtSameAddrSubDistrict.Text);
                _nonggpackage.MailingDistrict = Server.HtmlEncode(txtSameAddrStateProvince.Text);
                _nonggpackage.MailingProvince = Server.HtmlEncode(txtSameAddrProvince.Text);
                _nonggpackage.MailingPostalCode = txtSameAddrPostalCode.Text;
                _nonggpackage.MailingName = txtSameAddrName.Text;
            }

            _nonggpackage.Package = Server.HtmlEncode(txtPackage.Text);
            _nonggpackage.NoOfDriver = Convert.ToInt16(ddlNamedDriver.Text);
            _nonggpackage.InsuranceType = Convert.ToInt32(ddlInsuranceType.Text);
            //Yui@22/01/2015
            if (chkMile.Checked)
                _nonggpackage.Mile = 1;
            else
                _nonggpackage.Mile = 0;
            //End

            _nonggpackage.GarageType = Convert.ToInt32(ddlGarageType.Text);
            _nonggpackage.CarYear = Convert.ToInt32(txtCarModelYear.Text);
            _nonggpackage.CarModel = Server.HtmlEncode(txtCarMakeModel.Text);
          
            _nonggpackage.Beneficiary = Server.HtmlEncode(txtBeneficiary.Text);
            _nonggpackage.VehicleType = Convert.ToInt32(ddlVehicleType.Text);
          
            Int32 _outSumInsurred = 0;
            if (!Int32.TryParse(txtSumInsured.Text, out _outSumInsurred))
            {
                _outSumInsurred = 0;
            }
            _nonggpackage.SumInsured = _outSumInsurred;
            _nonggpackage.NCB = Convert.ToInt32(ddlNCB.Text);
            _nonggpackage.CurrentInsurer = Server.HtmlEncode(txtCurrentInsurer.Text);
            _nonggpackage.CarPlate = Server.HtmlEncode(txtPlateNumber.Text);
            _nonggpackage.CarPlateProvince = Server.HtmlEncode(txtRegistrationProvince.Text);
            _nonggpackage.EngineNumber = Server.HtmlEncode(txtEngineNumber.Text);
            _nonggpackage.ChassisNumber = Server.HtmlEncode(txtChassisNumber.Text);
          
            _nonggpackage.CoverageStart = _dtCommDate;
            DateTime _dtPolicyDate = new DateTime(Convert.ToInt32(ddlPolicyYear.Text), Convert.ToInt32(ddlPolicyMonth.Text), Convert.ToInt32(ddlPolicyDay.Text));
            _nonggpackage.CTPLStart = _dtPolicyDate;

            _nonggpackage.Premium = Convert.ToSingle(txtInsurancePremium.Text);
            _nonggpackage.IsCTPL = GetBoolean(Convert.ToInt16(ddlCTPL.Text));
            _nonggpackage.CTPL = Convert.ToSingle(txtCTPL.Text);

            _nonggpackage.TotalCollectedPremium = Convert.ToSingle(txtCollectedAmount.Text);
            _nonggpackage.TotalPremium = Convert.ToSingle(txtTotalPremium.Text);
            _nonggpackage.TermPremium = Convert.ToSingle(txtTotalPremium.Text);
          
            _nonggpackage.QuoteRefNo = txtNewQuoteRefNo.Text;
            _nonggpackage.Status = true;
            _nonggpackage.RefCEUserId = Convert.ToInt64(txtUserId.Text);
            if (Session[CE.Global.General.UserRole] != null && Session[CE.Global.General.UserRole].ToString() == "100")
            {
                _nonggpackage.AgentId = Convert.ToInt64(Session[CE.Global.General.UserId].ToString());
                _nonggpackage.AdminId = _AdminId;
            }
            else
            {
                if (_AgentId == 0)
                {
                    _nonggpackage.AgentId = Convert.ToInt64(Session[CE.Global.General.UserId].ToString());
                }
                else
                {
                    _nonggpackage.AgentId = _AgentId;
                }

                _nonggpackage.AdminId = Convert.ToInt64(Session[CE.Global.General.UserId].ToString());
            }
            _nonggpackage.Info1 = ddlApplicationType.Text;
            if (ddlApplicationType.Text == "REN" || ddlApplicationType.Text == "CHB")
            {
                _nonggpackage.Info2 = txtLastYearPolicyNo.Text.Trim();
            }
            if (_nonggpackage.ProviderCompanyId == 43)
            {
                _nonggpackage.Info3 = txtInsurerEmail.Text.Trim();
            }
            if (chkIsCreditCardOwner.Checked)
            {
                _nonggpackage.IsCreditCardOwner = 1;
            }
            if (chkPromotion.Checked)
            {
                _nonggpackage.PromotionCode = "1";
            }
            if (trModificationAmount.Visible == true)
            {
                _nonggpackage.Info4 = Server.HtmlEncode(txtModificationAmount.Text.Trim());
            }
            _nonggpackage.Info8 = Server.HtmlEncode(txtAgentRemarkDetails.Text);
            _result = _nonggpackagedb.Insert(_nonggpackage,true);
            Int32 driverresult = 0;
            if (_result > 0)
            {
                MyDatabase _db = new MyDatabase();
                string strUpdate = "Update tblCEContact SET OtherContact2 = @OtherContact2 Where RefCEUserID = @CustomerID";
                SortedList _paraList = new SortedList();
                _paraList.Add("@OtherContact2", Server.HtmlEncode(txtOtherContactNumber.Text.Trim()));
                _paraList.Add("@CustomerID", txtUserId.Text);
                int _retValue = _db.ExecuteNonSqlStatement(strUpdate, _paraList);

                // Renew Ext Com Date
                string _strUpdateSQL = "UPDATE tblCarDetailTH SET ";
                if (dteExtCommDate != null)
                {
                    _strUpdateSQL += " Dinfo2 = '" + dteExtCommDate.Value.ToString("yyyy-MM-dd") + "' ";
                }
                else
                {
                    _strUpdateSQL += " Dinfo2 = NULL ";
                }
                _strUpdateSQL += " WHERE CarID = " + txtCarId.Text + " AND RefCEUserID = " + txtUserId.Text;
                _retValue = _db.ExecuteNonSqlStatement(_strUpdateSQL);
                //*******************

                if (Convert.ToInt16(ddlNamedDriver.Text) > 0)
                {
                    if (SaveDriverDetails())
                    {
                        driverresult = 1;
                        pnlCarDetails.Visible = false;
                        lblOptionMessage.Text = Resources.CarInsurance.SuccessfullySaved;
                        pnlOptionMessage.Visible = true;
                        pnlDetails.Visible = true;
                        divCar.Visible = true;
                    }
                    else
                    {
                        driverresult = 0;
                    }
                }
                else
                {
                    driverresult = 1;
                }

                if (driverresult > 0)
                {
                    string _fileName = lblUpRefNo.Text.Trim() + "_" + dateTimeNow.Day.ToString("00") + "-" + dateTimeNow.Month.ToString("00") + "-" + dateTimeNow.Year;
                    string _filePath = GetExcelFilePath(Convert.ToInt64(txtProviderId.Text.Trim()), lblUpRefNo.Text.Trim());
                    string ExcelFile = GenerateNonGGExcel(_nonggpackage.CECarId, _nonggpackage.ProviderCompanyId, _filePath, _fileName);
                    if (ExcelFile != null)
                    {
                        Int64 _excelResult = -1;
                        _excelResult = _nonggpackagedb.UpdateExcelName(_nonggpackage.CECarId, ExcelFile);
                    }
                }
            }

            lblOptionError.Text = Resources.CarInsurance.SuccessfullySaved;
        }
        else
        {
            lblOptionError.Text = Resources.CarInsurance.SuccessfullySaved;
            pnlOptionMessage.Visible = true;
        }
    }

    protected void ddlApplicationType_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlApplicationType.Text == "NEW")
        {
            lblLastYearPolicyNoTitle.Text = string.Empty;
            rfvLastYearPolicyNo.Enabled = false;
            txtLastYearPolicyNo.Visible = false;
            txtLastYearPolicyNo.Text = "";
            txtLastYearPolicyNo.Enabled = true;
        }
        else if (ddlApplicationType.Text == "REN")
        {
            lblLastYearPolicyNoTitle.Text = Resources.Proposal.LastYearPolicyNo;
            rfvLastYearPolicyNo.Enabled = true;
            txtLastYearPolicyNo.Visible = true;
            txtLastYearPolicyNo.Text = lblLastYearPolicyNo.Text;
            txtLastYearPolicyNo.Enabled = false;
        }
        else if (ddlApplicationType.Text == "RNO")
        {
            lblLastYearPolicyNoTitle.Text = string.Empty;
            rfvLastYearPolicyNo.Enabled = false;
            txtLastYearPolicyNo.Visible = false;
            txtLastYearPolicyNo.Text = "";
            txtLastYearPolicyNo.Enabled = true;
        }
        else if (ddlApplicationType.Text == "CHB")
        {
            lblLastYearPolicyNoTitle.Text = Resources.Proposal.LastYearPolicyNo;
            rfvLastYearPolicyNo.Enabled = true;
            txtLastYearPolicyNo.Visible = true;
            txtLastYearPolicyNo.Text = "";
            txtLastYearPolicyNo.Enabled = true;
            if (lblNonGGStatus.Text == "1")
            {
                txtLastYearPolicyNo.Text = lblLastYearPolicyNo.Text;
            }
        }
    }

    protected void ddlCTPL_SelectedIndexChanged(object sender, EventArgs e)
    {
        float TotalPremium = Convert.ToSingle(txtInsurancePremium.Text);
        if (ddlCTPL.Text == "1")
        {
            TotalPremium = Convert.ToSingle(txtInsurancePremium.Text) + Convert.ToSingle(txtCTPL.Text);
        }
        txtTotalPremium.Text = TotalPremium.ToString("#0.00");
    }

    protected void ddlNamedDriver_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (Convert.ToInt16(ddlNamedDriver.Text) == 0)
        {
            rfvDriverFirst.Enabled = false;
            revDriverFirst.Enabled = false;
            rfvDriver1IDNo.Enabled = false;
            rfvDriver1LicenseNo.Enabled = false;
            rfvDriverTwo.Enabled = false;
            revDriverTwo.Enabled = false;
            rfvDriver2IDNo.Enabled = false;
            rfvDriver2LicenseNo.Enabled = false;

            ddlDriver1DOBDay.Enabled = false;
            ddlDriver1DOBMonth.Enabled = false;
            ddlDriver1DOBYear.Enabled = false;
            txtDriverFirst.Enabled = false;
            txtDriver1IDNo.Enabled = false;
            txtDriver1LicenseNo.Enabled = false;
            ddlDriver2DOBDay.Enabled = false;
            ddlDriver2DOBMonth.Enabled = false;
            ddlDriver2DOBYear.Enabled = false;
            txtDriverTwo.Enabled = false;
            txtDriver2IDNo.Enabled = false;
            txtDriver2LicenseNo.Enabled = false;
        }
        else if (Convert.ToInt16(ddlNamedDriver.Text) == 1)
        {
            rfvDriverFirst.Enabled = true;
            revDriverFirst.Enabled = true;
            rfvDriver1IDNo.Enabled = true;
            rfvDriver1LicenseNo.Enabled = true;
            rfvDriverTwo.Enabled = false;
            revDriverTwo.Enabled = false;
            rfvDriver2IDNo.Enabled = false;
            rfvDriver2LicenseNo.Enabled = false;

            ddlDriver1DOBDay.Enabled = true;
            ddlDriver1DOBMonth.Enabled = true;
            ddlDriver1DOBYear.Enabled = true;
            txtDriverFirst.Enabled = true;
            txtDriver1IDNo.Enabled = true;
            txtDriver1LicenseNo.Enabled = true;
            ddlDriver2DOBDay.Enabled = false;
            ddlDriver2DOBMonth.Enabled = false;
            ddlDriver2DOBYear.Enabled = false;
            txtDriverTwo.Enabled = false;
            txtDriver2IDNo.Enabled = false;
            txtDriver2LicenseNo.Enabled = false;
        }
        else if (Convert.ToInt16(ddlNamedDriver.Text) == 2)
        {
            rfvDriverFirst.Enabled = true;
            revDriverFirst.Enabled = true;
            rfvDriver1IDNo.Enabled = true;
            rfvDriver1LicenseNo.Enabled = true;
            rfvDriverTwo.Enabled = true;
            revDriverTwo.Enabled = true;
            rfvDriver2IDNo.Enabled = true;
            rfvDriver2LicenseNo.Enabled = true;

            ddlDriver1DOBDay.Enabled = true;
            ddlDriver1DOBMonth.Enabled = true;
            ddlDriver1DOBYear.Enabled = true;
            txtDriverFirst.Enabled = true;
            txtDriver1IDNo.Enabled = true;
            txtDriver1LicenseNo.Enabled = true;
            ddlDriver2DOBDay.Enabled = true;
            ddlDriver2DOBMonth.Enabled = true;
            ddlDriver2DOBYear.Enabled = true;
            txtDriverTwo.Enabled = true;
            txtDriver2IDNo.Enabled = true;
            txtDriver2LicenseNo.Enabled = true;
        }
        lblLoadMessage.Text = string.Empty;
    }

    protected void ddlOption_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            lblFinanceUserAlert.Text = "";
            lblCashierApproveMessage.Text = "";
            lblPayError.Text = "";
            lblOnlinePayError.Text = "";
            Span1.InnerHtml = "";
            txtRemark.Text = "";
            ClearPayFields();
            lblOptionError.Text = string.Empty;
            if (ddlOption.Text == "EDIT")
            {
                if (Session[General.UserRole] != null && Session[General.UserRole].ToString() == "201")
                {
                    Response.Redirect("~/carinsurance/PendingApplication.aspx");
                }

                lblOptionError.Text = string.Empty;
                lblOptionMessage.Text = string.Empty;
                ScriptManager.RegisterStartupScript(ddlOption, ddlOption.GetType(), Guid.NewGuid().ToString(), "ShowHideDiv('divUpload',false);", true);

                pnlDetails.Visible = true;
                pnlCarDetails.Visible = true;
                pnlPayment.Visible = false;
                pnlApplicationCancel.Visible = false;
                pnlApplicationRetrieve.Visible = false;
                pnlUploadFileList.Visible = false;
                pnlPaymentApproval.Visible = false;

                DataSet _dsPayment = GetPaymentAmounts();
                if (_dsPayment != null && _dsPayment.Tables.Count > 0 && _dsPayment.Tables[0].Rows.Count > 0)
                {
                    txtTotalPremium.Text = _dsPayment.Tables[0].Rows[0]["TotalPremium"].ToString();
                    txtCollectedAmount.Text = _dsPayment.Tables[0].Rows[0]["FinalPrice"].ToString();
                    if (_dsPayment.Tables[0].Rows[0]["TotalPremium"] != DBNull.Value &&
                        _dsPayment.Tables[0].Rows[0]["TotalPremium"].ToString() != string.Empty &&
                        _dsPayment.Tables[0].Rows[0]["PaymentOption"].ToString() != "FP")
                    {
                        lblBalanceAmount.Text = _dsPayment.Tables[0].Rows[0]["BalanceAmountWOD"].ToString();
                    }
                    else
                    {
                        lblBalanceAmount.Text = _dsPayment.Tables[0].Rows[0]["BalanceAmount"].ToString();
                    }
                }
                else
                {
                    lblBalanceAmount.Text = txtTotalPremium.Text;
                }
                if (pnlCarDetails.Visible == true)
                {
                    ddlOption.Text = "EDIT";
                }
            }
            else if (ddlOption.Text == "PAYM")
            {
                if (Session[General.UserRole] != null && Session[General.UserRole].ToString() == "201")
                {
                    Response.Redirect("~/carinsurance/PendingApplication.aspx");
                }
                pnlPaymentApproval.Visible = false;
                divAgentComments.Visible = false;
                if (Session[General.UserRole] != null && Session[General.UserRole].ToString() == "300")
                {
                    pnlPaymentApproval.Visible = true;
                    divAgentComments.Visible = true;

                    txtApprovalDate.Text = dateTimeNow.ToString("dd-MMM-yyyy");
                    cexApprovalDate.StartDate = dateTimeNow.AddMonths(-3);
                    cexApprovalDate.EndDate = dateTimeNow;
                }
                //Sakthi 14 Jun 2012 -Start
                chkApprove.Enabled = false;
                chkRefund.Enabled = false;
                //Sakthi 14 Jun 2012 -End
                txtOnlineApproveStatus.Text = "0";
                lblOptionError.Text = string.Empty;
                lblOptionMessage.Text = string.Empty;
                ScriptManager.RegisterStartupScript(ddlOption, ddlOption.GetType(), Guid.NewGuid().ToString(), "ShowHideDiv('divUpload',false);", true);
                pnlDetails.Visible = true;
                pnlCarDetails.Visible = false;
                pnlPayment.Visible = true;
                pnlApplicationCancel.Visible = false;
                pnlApplicationRetrieve.Visible = false;
                pnlUploadFileList.Visible = false;

                txtBalanceAmount.Text = "0";
                lblPayBalance.Text = "0";
                txtTotalCollectedAmount.Text = "0";
                txtTotalRefundAmount.Text = "0";
                DataSet _dsPayment = new DataSet();
                _dsPayment = GetBrokerPremium();
                ddlNoOfInstallments.Items.Clear();
                //ddlPaymentOption.Text = "FP";

                //*** Yui@05/01/2014 ***
                //ddlPaymentOption.Items.Clear();
                //ddlPaymentOption.Items.Add(new ListItem(Resources.CarInsurance.AnnualPayment, "FP"));
                ddlPaymentOption.SelectedIndex = ddlPaymentOption.Items.IndexOf(ddlPaymentOption.Items.FindByValue("FP"));
                // **********************

                if (_dsPayment != null && _dsPayment.Tables.Count > 0 && _dsPayment.Tables[0].Rows.Count > 0)
                {
                    lblPaymentMode.Text = "";
                    if (_dsPayment.Tables[0].Rows[0]["PaymentMode"] != DBNull.Value)
                    {
                        if (_dsPayment.Tables[0].Rows[0]["PaymentMode"].ToString() == "CR")
                            lblPaymentMode.Text = "Credit Card";
                        else if (_dsPayment.Tables[0].Rows[0]["PaymentMode"].ToString() == "TR")
                            lblPaymentMode.Text = "โอนเงิน";
                    }

                    txtAgentComments.Text = "";
                    if (_dsPayment.Tables[0].Rows[0]["Info8"] != DBNull.Value && _dsPayment.Tables[0].Rows[0]["Info8"].ToString() != string.Empty)
                    {
                        txtAgentComments.Text = _dsPayment.Tables[0].Rows[0]["Info8"].ToString();
                    }

                    //*** Yui@05/01/2014 ***
                    if (_dsPayment.Tables[0].Rows[0]["Bank"] != DBNull.Value)
                        txtCreditCard.Text = _dsPayment.Tables[0].Rows[0]["Bank"].ToString();

                    if (_dsPayment.Tables[0].Rows[0]["ProviderCoverTypeId"] != DBNull.Value)
                        txtCoverTypeId.Text = _dsPayment.Tables[0].Rows[0]["ProviderCoverTypeId"].ToString();
                    //**********************

                    //*** Yui@05/01/2014 ***
                    if (_dsPayment.Tables[0].Rows[0]["PaymentOption"] != DBNull.Value && _dsPayment.Tables[0].Rows[0]["PaymentOption"].ToString() != "-1")
                    {
                        if (_dsPayment.Tables[0].Rows[0]["PaymentOption"].ToString().ToUpper() == "FP")
                        {
                            //ddlPaymentOption.Items.Clear();
                            //ddlPaymentOption.Items.Add(new ListItem(Resources.CarInsurance.AnnualPayment, "FP"));
                            ddlPaymentOption.SelectedIndex = ddlPaymentOption.Items.IndexOf(ddlPaymentOption.Items.FindByValue("FP"));
                        }
                        else if (_dsPayment.Tables[0].Rows[0]["PaymentOption"].ToString().ToUpper() == "IP")
                        {
                            //ddlPaymentOption.Items.Clear();
                            //ddlPaymentOption.Items.Add(new ListItem(Resources.CarInsurance.Installment, "IP"));
                            ddlPaymentOption.SelectedIndex = ddlPaymentOption.Items.IndexOf(ddlPaymentOption.Items.FindByValue("IP"));
                        }
                    }
                    //ddlPaymentOption.Enabled = false;
                    // **********************
                    if (ddlPaymentOption.Text == "IP")
                    {
                        if (_dsPayment.Tables[0].Rows[0]["NoofInstallment"] != DBNull.Value && _dsPayment.Tables[0].Rows[0]["NoofInstallment"].ToString() != "-1")
                        {
                            //*** Yui@05/01/2014 ***
                            //ddlNoOfInstallments.Items.Clear();
                            //ddlNoOfInstallments.Items.Add(new ListItem(_dsPayment.Tables[0].Rows[0]["NoofInstallment"].ToString(), _dsPayment.Tables[0].Rows[0]["NoofInstallment"].ToString()));
                            txtNoOfInstallment.Text = _dsPayment.Tables[0].Rows[0]["NoofInstallment"].ToString();
                            //**********************
                        }
                        if (_dsPayment.Tables[0].Rows[0]["Bank"] != DBNull.Value && _dsPayment.Tables[0].Rows[0]["Bank"].ToString() != "-1")
                        {
                            ddlIssuingBank.Items.Clear();
                            ddlIssuingBank.Items.Add(new ListItem(GetBankName(_dsPayment.Tables[0].Rows[0]["Bank"].ToString()), _dsPayment.Tables[0].Rows[0]["Bank"].ToString()));
                            if (ddlIssuingBank.Text == "CHINS")
                            {
                                txtIssuingBank.Text = "Cash Installment";
                            }
                            else if (ddlIssuingBank.Text == "KBANK")
                            {
                                txtIssuingBank.Text = "Kasikorn Bank";
                            }
                            else if (ddlIssuingBank.Text == "BKK")
                            {
                                txtIssuingBank.Text = "Bangkok Bank";
                            }
                            else if (ddlIssuingBank.Text == "CITI")
                            {
                                txtIssuingBank.Text = "Citibank";
                            }
                            else if (ddlIssuingBank.Text == "KTC")
                            {
                                txtIssuingBank.Text = "KTC";
                            }
                            else if (ddlIssuingBank.Text == "AYA")
                            {
                                txtIssuingBank.Text = "Bank of Ayudhaya";
                            }
                            else if (ddlIssuingBank.Text == "CTRL")
                            {
                                txtIssuingBank.Text = "Central Card";
                            }
                            else if (ddlIssuingBank.Text == "RBSN")
                            {
                                txtIssuingBank.Text = "Robinson Card";
                            }
                            else if (ddlIssuingBank.Text == "HPRO")
                            {
                                txtIssuingBank.Text = "Homepro Card";
                            }
                        }

                        Int32 _Installments = Convert.ToInt32(txtNoOfInstallment.Text);
                        Int32 _Install = _Installments - 1;
                        decimal IPFinalAnnualPremiumWD = 0;
                        decimal InstallmentAmountWD = 0;
                        decimal LastInstallmentAmountWD = 0;
                        decimal IPFinalAnnualPremiumWOD = 0;
                        decimal InstallmentAmountWOD = 0;
                        decimal LastInstallmentAmountWOD = 0;
                        Int32 _Approved = 0;
                        if (_dsPayment.Tables[0].Rows[0]["Approved"] != DBNull.Value)
                        {
                            if (!Int32.TryParse(_dsPayment.Tables[0].Rows[0]["Approved"].ToString(), out _Approved))
                            {
                                _Approved = 0;
                            }
                        }
                        if (_Approved == 0)
                        {
                            if (_dsPayment.Tables[0].Rows[0]["IPFinalAnnualPremiumWD"] != DBNull.Value)
                            {
                                if (!decimal.TryParse(_dsPayment.Tables[0].Rows[0]["IPFinalAnnualPremiumWD"].ToString(), out IPFinalAnnualPremiumWD))
                                {
                                    IPFinalAnnualPremiumWD = 0;
                                }
                                txtOnlineAmount.Text = IPFinalAnnualPremiumWD.ToString("#000.00");
                            }
                            if (_dsPayment.Tables[0].Rows[0]["IPFinalAnnualPremiumWD"] != DBNull.Value)
                            {
                                if (!decimal.TryParse(_dsPayment.Tables[0].Rows[0]["InstallmentAmountWD"].ToString(), out InstallmentAmountWD))
                                {
                                    InstallmentAmountWD = 0;
                                }
                                txtOnlineAmount.Text = InstallmentAmountWD.ToString("#000.00");
                            }
                            if (_dsPayment.Tables[0].Rows[0]["IPFinalAnnualPremiumWD"] != DBNull.Value)
                            {
                                if (!decimal.TryParse(_dsPayment.Tables[0].Rows[0]["LastInstallmentAmountWD"].ToString(), out LastInstallmentAmountWD))
                                {
                                    LastInstallmentAmountWD = 0;
                                }
                                txtOnlineAmount.Text = LastInstallmentAmountWD.ToString("#000.00");
                            }

                            if (_dsPayment.Tables[0].Rows[0]["IPFinalAnnualPremiumWOD"] != DBNull.Value)
                            {
                                if (!decimal.TryParse(_dsPayment.Tables[0].Rows[0]["IPFinalAnnualPremiumWOD"].ToString(), out IPFinalAnnualPremiumWOD))
                                {
                                    IPFinalAnnualPremiumWOD = 0;
                                }
                                txtOnlineAmount.Text = IPFinalAnnualPremiumWOD.ToString("#000.00");
                            }
                            if (_dsPayment.Tables[0].Rows[0]["IPFinalAnnualPremiumWOD"] != DBNull.Value)
                            {
                                if (!decimal.TryParse(_dsPayment.Tables[0].Rows[0]["InstallmentAmountWOD"].ToString(), out InstallmentAmountWOD))
                                {
                                    InstallmentAmountWOD = 0;
                                }
                                txtOnlineAmount.Text = InstallmentAmountWOD.ToString("#000.00");
                            }
                            if (_dsPayment.Tables[0].Rows[0]["IPFinalAnnualPremiumWOD"] != DBNull.Value)
                            {
                                if (!decimal.TryParse(_dsPayment.Tables[0].Rows[0]["LastInstallmentAmountWOD"].ToString(), out LastInstallmentAmountWOD))
                                {
                                    LastInstallmentAmountWOD = 0;
                                }
                                txtOnlineAmount.Text = LastInstallmentAmountWOD.ToString("#000.00");
                            }

                            if (ddlIssuingBank.Text != "CHINS")
                            {
                                lblAmountwithInterestTitle.Text = Resources.CarInsurance.TotalAmountwithInterest;
                                lblInstallmentListTitle.Text = "1 " + Resources.CarInsurance.To + " " + _Install.ToString() + " " + Resources.CarInsurance.Months;
                                lblLastInstallmentTitle.Text = Resources.CarInsurance.LastMonthInstallment;
                            }
                            else
                            {
                                lblAmountwithInterestTitle.Text = Resources.CarInsurance.TotalAmountwithInterest;
                                lblInstallmentListTitle.Text = "1st " + Resources.CarInsurance.Month;
                                if (_Install <= 1)
                                {
                                    lblLastInstallmentTitle.Text = Resources.CarInsurance.LastMonthInstallment;
                                }
                                else
                                {
                                    lblLastInstallmentTitle.Text = "Last " + _Install + " " + Resources.CarInsurance.Months;
                                }
                            }

                            lblAmountwithInterest.Text = IPFinalAnnualPremiumWOD.ToString("#.00");
                            lblInstallmentList.Text = InstallmentAmountWOD.ToString("#.00");
                            lblLastInstallment.Text = LastInstallmentAmountWOD.ToString("#.00");

                            //if (txtIsWD.Text == "1")
                            //{
                            //    //if (txtProviderId.Text == "29" && ddlIssuingBank.Text != "CHINS")
                            //    //{
                            //    //    lblAmountwithInterest.Text = IPFinalAnnualPremiumWD.ToString("#.00");
                            //    //    lblInstallmentList.Text = InstallmentAmountWD.ToString("#.00");
                            //    //    lblLastInstallment.Text = LastInstallmentAmountWD.ToString("#.00");
                            //    //}
                            //    //else
                            //    //{
                            //    lblAmountwithInterest.Text = IPFinalAnnualPremiumWOD.ToString("#.00");
                            //    lblInstallmentList.Text = InstallmentAmountWOD.ToString("#.00");
                            //    lblLastInstallment.Text = LastInstallmentAmountWOD.ToString("#.00");
                            //    //}
                            //}
                            //else
                            //{
                            //    lblAmountwithInterest.Text = IPFinalAnnualPremiumWOD.ToString("#.00");
                            //    lblInstallmentList.Text = InstallmentAmountWOD.ToString("#.00");
                            //    lblLastInstallment.Text = LastInstallmentAmountWOD.ToString("#.00");
                            //}
                        }
                        else
                        {
                            decimal _FinalApprovedPrice = 0;
                            decimal _InstallmentAmount = 0;
                            decimal _1stInstallment = 0;
                            decimal _LastInstallment = 0;
                            if (txtFinalPrice.Text.Trim() != "0")
                            {
                                if (!decimal.TryParse(txtFinalPrice.Text.Trim(), out _FinalApprovedPrice))
                                {
                                    _FinalApprovedPrice = 0;
                                }
                            }

                            _Installments = Convert.ToInt32(txtNoOfInstallment.Text);
                            _Install = _Installments - 1;
                            if (ddlIssuingBank.Text != "CHINS")
                            {
                                _InstallmentAmount = Math.Ceiling(Convert.ToDecimal(_FinalApprovedPrice / _Installments));
                                _1stInstallment = Convert.ToDecimal(_InstallmentAmount * _Install);
                                _LastInstallment = Convert.ToDecimal(_FinalApprovedPrice - _1stInstallment);

                                lblAmountwithInterest.Text = _FinalApprovedPrice.ToString("#.00");
                                lblInstallmentList.Text = _InstallmentAmount.ToString("#.00");
                                lblLastInstallment.Text = _LastInstallment.ToString("#.00");

                                lblAmountwithInterestTitle.Text = Resources.CarInsurance.TotalAmountwithInterest;
                                lblInstallmentListTitle.Text = "1 " + Resources.CarInsurance.To + " " + _Install.ToString() + " " + Resources.CarInsurance.Months;
                                lblLastInstallmentTitle.Text = Resources.CarInsurance.LastMonthInstallment;
                            }
                            else
                            {
                                decimal tempInstall = 0;
                                if (_Installments == 2)
                                {
                                    tempInstall = Convert.ToDecimal(_FinalApprovedPrice / 10);
                                    _LastInstallment = Math.Ceiling(Convert.ToDecimal(tempInstall * 5));
                                    _1stInstallment = (_FinalApprovedPrice - _LastInstallment);
                                }
                                else if (_Installments == 3)
                                {
                                    tempInstall = Convert.ToDecimal(_FinalApprovedPrice / 10);
                                    _LastInstallment = Math.Ceiling(Convert.ToDecimal(tempInstall * 3));
                                    _1stInstallment = (_FinalApprovedPrice - (_LastInstallment * 2));
                                }
                                else if (_Installments == 4)
                                {
                                    tempInstall = Convert.ToDecimal(_FinalApprovedPrice / 4);
                                    _LastInstallment = Math.Ceiling(tempInstall);
                                    _1stInstallment = (_FinalApprovedPrice - (_LastInstallment * 3));
                                }

                                lblAmountwithInterest.Text = _FinalApprovedPrice.ToString("#.00");
                                lblInstallmentList.Text = _1stInstallment.ToString("#.00");
                                lblLastInstallment.Text = _LastInstallment.ToString("#.00");

                                lblAmountwithInterestTitle.Text = Resources.CarInsurance.TotalAmountwithInterest;
                                lblInstallmentListTitle.Text = "1st " + Resources.CarInsurance.Month;
                                if (_Install <= 1)
                                {
                                    lblLastInstallmentTitle.Text = Resources.CarInsurance.LastMonthInstallment;
                                }
                                else
                                {
                                    lblLastInstallmentTitle.Text = "Last " + _Install + " " + Resources.CarInsurance.Months;
                                }
                            }
                        }

                    }
                }

                ddlPaymentOption_SelectedIndexChanged(null, null);
                
                if (_dsPayment != null && _dsPayment.Tables.Count > 1 && _dsPayment.Tables[1].Rows.Count > 0)
                {
                    grvPayment.DataSource = _dsPayment.Tables[1];
                    grvPayment.DataBind();
                    txtPaymentId.Text = "0";
                    EnableDisable();
                    if (grvPayment.Rows.Count > 0)
                    {
                        btnPaymentApproval.Enabled = true;
                        chkRefund.Enabled = true;
                        chkApprove.Enabled = false;
                        DataSet _dsPaymentAmount = new DataSet();
                        _dsPaymentAmount = GetPaymentAmounts();
                        if (_dsPaymentAmount != null && _dsPaymentAmount.Tables.Count > 0 && _dsPaymentAmount.Tables[0].Rows.Count > 0)
                        {
                            txtTescoAmount.Text = _dsPaymentAmount.Tables[0].Rows[0]["TescoAmountShow"].ToString();
                            txtFinalApprovalPremium.Text = _dsPaymentAmount.Tables[0].Rows[0]["FinalPrice"].ToString();
                            txtTescoPaymentId.Text = _dsPaymentAmount.Tables[0].Rows[0]["TescoPaymentId"].ToString();
                            txtSpecialPaymentId.Text = _dsPaymentAmount.Tables[0].Rows[0]["SpecialPaymentId"].ToString();
                            txtApprovalRemark.Text = _dsPaymentAmount.Tables[0].Rows[0]["SpecialRemarks"].ToString();

                            txtTotalCollectedAmount.Text = _dsPaymentAmount.Tables[0].Rows[0]["CollectedAmount"].ToString();
                            txtTotalRefundAmount.Text = _dsPaymentAmount.Tables[0].Rows[0]["RefundAmount"].ToString();
                        }
                        divPayList.Visible = true;

                    }
                    else
                    {
                        divPayList.Visible = false;
                        grvPayment.DataSource = null;
                        grvPayment.DataBind();
                    }
                }
                else
                {
                    txtWDPremium.Text = lblUpPremiumWD.Text;
                    txtWODPremium.Text = lblUpPremiumWOD.Text;

                    txtTescoPaymentId.Text = "0";
                    txtSpecialPaymentId.Text = "0";
                    txtApprovalRemark.Text = "";
                }
                if (txtPaymentId.Text == "0")
                {
                    chkRefund.Enabled = true;
                }
                else
                {
                    chkRefund.Enabled = false;
                }

                float _onlineAmount = 0.0f;
                DataSet _dsApplication = new DataSet();
                NonGGPackageDB _nonggpackagedb = new NonGGPackageDB();
                _dsApplication = _nonggpackagedb.GetCarDetails(Convert.ToInt64(txtCarId.Text.Trim()), Convert.ToInt64(txtUserId.Text.Trim()));

                //*** Yui@05/01/2014 ***
                DateTime Commdate = dateTimeNow;
                if (_dsApplication.Tables[0].Rows[0]["CoverageCommenceDate"] != DBNull.Value && _dsApplication.Tables[0].Rows[0]["CoverageCommenceDate"].ToString() != string.Empty)
                {
                    Commdate = Convert.ToDateTime(_dsApplication.Tables[0].Rows[0]["CoverageCommenceDate"].ToString());
                    txtCoverageDate.Text = Convert.ToDateTime(_dsApplication.Tables[0].Rows[0]["CoverageCommenceDate"]).ToString("dd/MMM/yyyy");
                }
                //**********************

                if (_dsApplication.Tables[2].Rows.Count > 0 && _dsApplication.Tables[2].Rows[0]["ONLPaymentStatus"] != DBNull.Value && _dsApplication.Tables[2].Rows[0]["ONLPaymentStatus"].ToString() != string.Empty
                    && _dsApplication.Tables[2].Rows[0]["ONLPaymentStatus"].ToString().ToUpper() == "1")
                {
                    if (_dsApplication.Tables[2].Rows[0]["DeclineStatus"] != DBNull.Value && _dsApplication.Tables[2].Rows[0]["DeclineStatus"].ToString() != string.Empty
                    && _dsApplication.Tables[2].Rows[0]["DeclineStatus"].ToString() == "1")
                    {
                        pnlPaymentInput.Visible = true;
                        lblOnlinePayError.Text = Resources.General.OnlinePaymentDecline;

                        btnOnlinePaySubmit.Visible = false;
                        btnOnlinePayDecline.Visible = false;
                    }
                    else
                    {
                        PaymentsDB _paymentsdb = new PaymentsDB();
                        DataSet _dsOLPayments = new DataSet();
                        _dsOLPayments = _paymentsdb.GetPayments(Convert.ToInt64(txtCarId.Text), 1);
                        if (_dsOLPayments != null && _dsOLPayments.Tables[0].Rows.Count > 0)
                        {
                            pnlPaymentInput.Visible = true;
                            txtOnlineApproveStatus.Text = "1";
                            lblOnlinePayError.Text = Resources.General.OnlinePaymentApprove;

                            btnOnlinePaySubmit.Visible = false;
                            btnOnlinePayDecline.Visible = false;
                        }
                        else
                        {
                            grvPayment.Enabled = false;
                            pnlPaymentInput.Visible = false;

                            btnOnlinePaySubmit.Visible = true;
                            btnOnlinePayDecline.Visible = true;
                        }
                    }

                    if (_dsApplication.Tables[2].Rows[0]["ONLPaymentCode"] != DBNull.Value && _dsApplication.Tables[2].Rows[0]["ONLPaymentCode"].ToString() != string.Empty
                        && _dsApplication.Tables[2].Rows[0]["ONLPaymentCode"].ToString() == "1")
                    {
                        pnlOnlinePayment.Visible = true;
                        txtOnlinePaymentType.Text = "CreditCard";
                        if (_dsApplication.Tables[2].Rows[0]["FinalAnnualPremium"] != DBNull.Value && _dsApplication.Tables[2].Rows[0]["FinalAnnualPremium"].ToString() != string.Empty)
                        {
                            _onlineAmount = Convert.ToSingle(_dsApplication.Tables[2].Rows[0]["FinalAnnualPremium"].ToString());
                            txtOnlineAmount.Text = _onlineAmount.ToString("#000.00");
                            txtAppStatus.Text = "OFFLINE";
                        }
                        else
                        {
                            txtOnlineAmount.Text = "0";
                        }
                        if (_dsApplication.Tables[2].Rows[0]["OrderRefNo"] != DBNull.Value && _dsApplication.Tables[2].Rows[0]["OrderRefNo"].ToString() != string.Empty)
                        {
                            txtOnlinePaymentRefNo.Text = _dsApplication.Tables[2].Rows[0]["OrderRefNo"].ToString();
                        }
                        else
                        {
                            txtOnlinePaymentRefNo.Text = "";
                        }
                    }
                    else
                    {
                        pnlPaymentInput.Visible = true;
                        pnlOnlinePayment.Visible = false;
                        txtOnlinePaymentType.Text = "ONLINE";
                        txtOnlineAmount.Text = "0";
                        txtOnlinePaymentRefNo.Text = "";
                    }
                }
                else if (_dsApplication != null && _dsApplication.Tables.Count > 4 && _dsApplication.Tables[4].Rows.Count > 0)
                {
                    if (_dsApplication.Tables[4].Rows[0]["DeclineStatus"] != DBNull.Value && _dsApplication.Tables[4].Rows[0]["DeclineStatus"].ToString() != string.Empty
                        && _dsApplication.Tables[4].Rows[0]["DeclineStatus"].ToString() == "1")
                    {
                        pnlPaymentInput.Visible = true;
                        lblOnlinePayError.Text = Resources.General.OnlinePaymentDecline;

                        btnOnlinePaySubmit.Visible = false;
                        btnOnlinePayDecline.Visible = false;
                    }
                    else
                    {
                        PaymentsDB _paymentsdb = new PaymentsDB();
                        DataSet _dsOLPayments = new DataSet();
                        _dsOLPayments = _paymentsdb.GetPayments(Convert.ToInt64(txtCarId.Text), 1);
                        if (_dsOLPayments != null && _dsOLPayments.Tables[0].Rows.Count > 0)
                        {
                            pnlPaymentInput.Visible = true;
                            txtOnlineApproveStatus.Text = "1";
                            lblOnlinePayError.Text = Resources.General.OnlinePaymentApprove;

                            btnOnlinePaySubmit.Visible = false;
                            btnOnlinePayDecline.Visible = false;
                        }
                        else
                        {
                            grvPayment.Enabled = false;
                            pnlPaymentInput.Visible = false;

                            btnOnlinePaySubmit.Visible = true;
                            btnOnlinePayDecline.Visible = true;
                        }
                    }

                    if (_dsApplication.Tables[4].Rows[0]["PaymentType"] != DBNull.Value && _dsApplication.Tables[4].Rows[0]["PaymentType"].ToString() != string.Empty
                        && _dsApplication.Tables[4].Rows[0]["PaymentType"].ToString().ToUpper() == "CREDITCARD")
                    {
                        if (_dsApplication.Tables[4].Rows[0]["PaymentCode"] != DBNull.Value && _dsApplication.Tables[4].Rows[0]["PaymentCode"].ToString() != string.Empty
                            && _dsApplication.Tables[4].Rows[0]["PaymentCode"].ToString() == "1")
                        {
                            pnlOnlinePayment.Visible = true;

                            txtOnlinePaymentType.Text = "CreditCard";
                            if (_dsApplication.Tables[4].Rows[0]["AnnualPremium"] != DBNull.Value && _dsApplication.Tables[4].Rows[0]["AnnualPremium"].ToString() != string.Empty)
                            {
                                _onlineAmount = Convert.ToSingle(_dsApplication.Tables[4].Rows[0]["AnnualPremium"].ToString());
                                txtOnlineAmount.Text = _onlineAmount.ToString("#000.00");
                                txtAppStatus.Text = "ONLINE";
                            }
                            else
                            {
                                txtOnlineAmount.Text = "0";
                            }
                            if (_dsApplication.Tables[4].Rows[0]["OrderRefNo"] != DBNull.Value && _dsApplication.Tables[4].Rows[0]["OrderRefNo"].ToString() != string.Empty)
                            {
                                txtOnlinePaymentRefNo.Text = _dsApplication.Tables[4].Rows[0]["OrderRefNo"].ToString();
                            }
                            else
                            {
                                txtOnlinePaymentRefNo.Text = "";
                            }
                        }
                        else
                        {
                            grvPayment.Enabled = true;
                            pnlPaymentInput.Visible = true;
                            pnlOnlinePayment.Visible = false;
                            txtOnlinePaymentType.Text = "ONLINE";
                            txtOnlineAmount.Text = "0";
                            txtOnlinePaymentRefNo.Text = "";
                        }
                    }
                    else
                    {
                        pnlOnlinePayment.Visible = true;
                        if (_dsApplication.Tables[4].Rows[0]["PaymentType"].ToString() == "Bank In")
                        {
                            txtOnlinePaymentType.Text = "BankTransfer";
                        }
                        else
                        {
                            txtOnlinePaymentType.Text = _dsApplication.Tables[4].Rows[0]["PaymentType"].ToString();
                        }

                        if (_dsApplication.Tables[4].Rows[0]["AnnualPremium"] != DBNull.Value && _dsApplication.Tables[4].Rows[0]["AnnualPremium"].ToString() != string.Empty)
                        {
                            _onlineAmount = Convert.ToSingle(_dsApplication.Tables[4].Rows[0]["AnnualPremium"].ToString());
                            txtOnlineAmount.Text = _onlineAmount.ToString("#000.00");
                            txtAppStatus.Text = "ONLINE";
                        }
                        else
                        {
                            txtOnlineAmount.Text = "0";
                        }
                        txtOnlinePaymentRefNo.Text = "";
                    }
                }
                else
                {
                    grvPayment.Enabled = true;
                    pnlPaymentInput.Visible = true;
                    pnlOnlinePayment.Visible = false;
                    txtOnlinePaymentType.Text = "ONLINE";
                    txtOnlineAmount.Text = "0";
                    txtOnlinePaymentRefNo.Text = "";
                }
                LoadLableColor();
                ShowTescoAmount();

                //*** Yui@05/01/2014 ***
                LoadCreditCard();
                //**********************

                //Approved  - Payment Complete
                LoadPaymentCompletedStatus();

                MyDatabase _db = new MyDatabase();
                string strSql = "SELECT AgentId, Email, FirstName FROM tblNonGGCarMoreDetails d INNER JOIN tblCEContact c ON c.RefCeUserID = d.AgentId INNER JOIN tblCEUsrProfile p ON p.RefCEUserId = c.RefCeUserID WHERE QuoteRefNo = '" + lblPRefNo.Text + "'";
                DataTable _dtAgentId = _db.GetDataTable(strSql);
                if (_dtAgentId.Rows.Count > 0)
                {
                    lblAgentName.Text = _dtAgentId.Rows[0]["FirstName"].ToString();
                    hidAgentEmail.Value = _dtAgentId.Rows[0]["Email"].ToString().Replace("_renewal", "");
                }
            }
            else if (ddlOption.Text == "UPLD")
            {
                ScriptManager.RegisterStartupScript(ddlOption, ddlOption.GetType(), Guid.NewGuid().ToString(), "ShowHideDiv('divUpload',true);", true);
                lblOptionError.Text = string.Empty;
                lblOptionMessage.Text = string.Empty;
                Span1.InnerHtml = "";
                pnlDetails.Visible = true;
                pnlUpload.Visible = true;
                pnlCarDetails.Visible = false;
                pnlPayment.Visible = false;
                pnlApplicationCancel.Visible = false;
                pnlApplicationRetrieve.Visible = false;
                pnlUploadFileList.Visible = false;
                pnlPaymentApproval.Visible = false;
                LoadUploadDocument();
            }
            else if (ddlOption.Text == "ACNL")
            {
                if (Session[General.UserRole] != null && Session[General.UserRole].ToString() == "201")
                {
                    Response.Redirect("~/carinsurance/PendingApplication.aspx");
                }

                ScriptManager.RegisterStartupScript(ddlOption, ddlOption.GetType(), Guid.NewGuid().ToString(), "ShowHideDiv('divUpload',false);", true);
                pnlDetails.Visible = true;
                pnlCarDetails.Visible = false;
                pnlPayment.Visible = false;
                pnlApplicationCancel.Visible = true;
                pnlApplicationRetrieve.Visible = false;
                pnlUploadFileList.Visible = false;
                pnlPaymentApproval.Visible = false;

                DataSet _dsApplication = new DataSet();
                NonGGPackageDB _nonggpackagedb = new NonGGPackageDB();
                _dsApplication = _nonggpackagedb.GetCarDetails(Convert.ToInt64(txtCarId.Text.Trim()), Convert.ToInt64(txtUserId.Text.Trim()));
                if (_dsApplication != null && _dsApplication.Tables.Count > 2 && _dsApplication.Tables[2].Rows.Count > 0)
                {
                    btnApplicationCancel.Enabled = true;
                    lblOptionError.Text = string.Empty;
                    lblOptionMessage.Text = string.Empty;
                }
                else
                {
                    pnlOptionMessage.Visible = true;
                    btnApplicationCancel.Enabled = false;
                    lblOptionError.Text = Resources.General.HaveNotSubmit;
                }
            }
            else if (ddlOption.Text == "RTRV")
            {
                lblOptionError.Text = string.Empty;
                lblOptionMessage.Text = string.Empty;
                ScriptManager.RegisterStartupScript(ddlOption, ddlOption.GetType(), Guid.NewGuid().ToString(), "ShowHideDiv('divUpload',false);", true);
                pnlDetails.Visible = true;
                pnlCarDetails.Visible = false;
                pnlPayment.Visible = false;
                pnlApplicationCancel.Visible = false;
                pnlApplicationRetrieve.Visible = true;
                pnlUploadFileList.Visible = false;
                pnlPaymentApproval.Visible = false;
            }
            else if (ddlOption.Text == "0")
            {
                lblOptionError.Text = string.Empty;
                ScriptManager.RegisterStartupScript(ddlOption, ddlOption.GetType(), Guid.NewGuid().ToString(), "ShowHideDiv('divUpload',false);", true);
                pnlDetails.Visible = true;
                pnlCarDetails.Visible = false;
                pnlPayment.Visible = false;
                pnlApplicationCancel.Visible = false;
                pnlApplicationRetrieve.Visible = false;
                pnlUploadFileList.Visible = false;
                pnlPaymentApproval.Visible = false;
            }

            lblLoadMessage.Text = string.Empty;
        }
        catch (Exception)
        {
            throw;
        }
        
    }

    protected void ddlPaymentType_SelectedIndexChanged(object sender, EventArgs e)
    {
        
        if (ddlPaymentType.Text == "CCOL" || ddlPaymentType.Text == "CCIP")
        {
            pnl123Service.Visible = false;
            pnlCreditCard.Visible = true;
            pnlBank.Visible = false;
            rfvBank.Enabled = false;
        }
        else if (ddlPaymentType.Text == "FAMT" ||
            ddlPaymentType.Text == "TESC" ||
            ddlPaymentType.Text == "TUMY")
        {
            //ddlPaymentType.Text == "SVEV"
            pnlBank.Visible = false;
            rfvBank.Enabled = false;
            pnlCreditCard.Visible = false;

            pnl123Service.Visible = true;
            chk123Service.Checked = true;
        }
        else
        {
            pnl123Service.Visible = false;
            pnlBank.Visible = false;
            rfvBank.Enabled = false;
            if (ddlPaymentType.Text == "BKTR")
            {
                pnlBank.Visible = true;
                rfvBank.Enabled = true;

                ddlBank.Items.Clear();
                ddlBank.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
                ddlBank.Items.Add(new ListItem(Resources.CarInsurance.BankBKK, "BKK"));
                ddlBank.Items.Add(new ListItem(Resources.CarInsurance.BankK, "KBANK"));
                ddlBank.Items.Add(new ListItem(Resources.CarInsurance.BankKTB, "KTB"));
                ddlBank.Items.Add(new ListItem(Resources.CarInsurance.BankSCB, "SCB"));

            }
            else if (ddlPaymentType.Text == "CHINS")
            {
                pnlBank.Visible = true;
                rfvBank.Enabled = true;

                ddlBank.Items.Clear();
                ddlBank.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
                ddlBank.Items.Add(new ListItem(Resources.CarInsurance.BankBKK, "BKK"));
                ddlBank.Items.Add(new ListItem(Resources.CarInsurance.BankK, "KBANK"));
                ddlBank.Items.Add(new ListItem(Resources.CarInsurance.BankKTB, "KTB"));
                ddlBank.Items.Add(new ListItem(Resources.CarInsurance.BankSCB, "SCB"));
                ddlBank.Items.Add(new ListItem(Resources.CarInsurance.Cash, "CASH"));

            }
            pnlCreditCard.Visible = false;
            if (txtPaymentId.Text != string.Empty && Convert.ToInt64(txtPaymentId.Text.Trim()) == 0)
            {
                if (ddlPaymentOption.Text != "IP")
                {
                    txtIssuingBank.Text = "";
                }
                if (ddlPaymentType.Text == "CHINS")
                {
                    txtIssuingBank.Text = "";
                }
                ddlCardType.SelectedIndex = 0;
                //txtCardHolder.Text = "";
                //txtCardNo1.Text = "";
                //txtCardNo2.Text = "";
                //txtCardNo3.Text = "";
                //txtCardNo4.Text = "";
                //txtCVV.Text = "000";
                //txtCardExpiryMonth.Text = "";
                //txtCardExpiryYear.Text = "";
            }
        }
        lblLoadMessage.Text = string.Empty;
    }

    protected void ddlPaymentOption_SelectedIndexChanged(object sender, EventArgs e)
    {
        
        if (ddlPaymentOption.Text == "IP")
        {
            if (ddlIssuingBank.Text == "CHINS")
            {                        
                ddlPaymentType.Items.Clear();
                
                ddlPaymentType.Items.Add(new ListItem(Resources.CarInsurance.CashInstallment, "CHINS"));
            }
            else
            {
                ddlPaymentType.Items.Clear();
                ddlPaymentType.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
                ddlPaymentType.Items.Add(new ListItem(Resources.CarInsurance.BankIn, "BKTR"));
                ddlPaymentType.Items.Add(new ListItem(Resources.CarInsurance.CreditcardiPay, "CCIP"));
                ddlPaymentType.Items.Add(new ListItem(Resources.CarInsurance.CreditcardAutodebit, "CCOL"));
            }

            ddlIssuingBank.Visible = true;
            divtxtIssuingBank.Visible = false;
            divddlIssuingBank.Visible = true;
            rfvIssuingBank.Enabled = false;
            rfvddlIssuingBank.Enabled = true;
            pnlNoOfInstallments.Visible = true;
            rfvNoOfInstallments.Enabled = true;

            txtAmount.Text = txtFinalPrice.Text;
            
        }
        else
        {
            ddlPaymentType.Items.Clear();
            ddlPaymentType.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
            ddlPaymentType.Items.Add(new ListItem(Resources.CarInsurance.Cash, "CASH"));
            ddlPaymentType.Items.Add(new ListItem(Resources.CarInsurance.BankIn, "BKTR"));
            ddlPaymentType.Items.Add(new ListItem(Resources.CarInsurance.CreditcardiPay, "CCIP"));
            ddlPaymentType.Items.Add(new ListItem(Resources.CarInsurance.CreditcardOnline, "CCOL"));
            //ddlPaymentType.Items.Add(new ListItem(Resources.CarInsurance.SevenEleven, "SVEV"));
            ddlPaymentType.Items.Add(new ListItem(Resources.CarInsurance.FamilyMart, "FAMT"));
            ddlPaymentType.Items.Add(new ListItem(Resources.CarInsurance.Tesco, "TESC"));
            ddlPaymentType.Items.Add(new ListItem(Resources.CarInsurance.TrueMoney, "TUMY"));

            ddlIssuingBank.Visible = false;
            divtxtIssuingBank.Visible = true;
            divddlIssuingBank.Visible = false;
            rfvIssuingBank.Enabled = true;
            rfvddlIssuingBank.Enabled = false;
            pnlNoOfInstallments.Visible = false;
            rfvNoOfInstallments.Enabled = false;

            txtAmount.Text = "";
            txtAmount.ReadOnly = false;
        }
        ddlPaymentType_SelectedIndexChanged(null, null);
        
        lblLoadMessage.Text = string.Empty;
    }

    protected void ddlIssuingBank_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlPaymentOption.Text == "IP")
        {
            if (ddlIssuingBank.Text == "KBANK")
            {
                txtIssuingBank.Text = "Kasikorn Bank";
            }
            else if (ddlIssuingBank.Text == "BKK")
            {
                txtIssuingBank.Text = "Bangkok Bank";
            }
            else if (ddlIssuingBank.Text == "CITI")
            {
                txtIssuingBank.Text = "Citibank";
            }
            else if (ddlIssuingBank.Text == "KTC")
            {
                txtIssuingBank.Text = "KTC";
            }
            else if (ddlIssuingBank.Text == "AYA")
            {
                txtIssuingBank.Text = "Bank of Ayudhaya";
            }
            else if (ddlIssuingBank.Text == "CTRL")
            {
                txtIssuingBank.Text = "Central Card";
            }
            else if (ddlIssuingBank.Text == "RBSN")
            {
                txtIssuingBank.Text = "Robinson Card";
            }
            else if (ddlIssuingBank.Text == "HPRO")
            {
                txtIssuingBank.Text = "Homepro Card";
            }
            else if (ddlIssuingBank.Text == "-1")
            {
                txtIssuingBank.Text = "";
            }
        }
    }

    private void LoadCreditCard()
    {
        ddlCreditCard.Items.Clear();
        ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
        if (txtProviderId.Text.Trim() == "11")
        {
            ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankCITI, "CITI"));
            ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankK, "KBANK"));
        }
        else if (txtProviderId.Text.Trim() == "29")
        {
            ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankK, "KBANK"));
        }
        else if (txtProviderId.Text.Trim() == "32")
        {
            ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankBKK, "BKK"));
            ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankCITI, "CITI"));
            ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankKTC, "KTC"));
            ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankAYA, "AYA"));
            ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.CentralCard, "CTRL"));
            ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.RobinsonCard, "RBSN"));
            ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.HomeproCard, "HPRO"));
            ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankK, "KBANK"));//Sakthi on 15 Nov 2012
        }
        else
        {
            ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankK, "KBANK"));
        }
        ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.CashInstallment, "CHINS"));

        // *** Fill in ***
        ddlCreditCard.SelectedIndex = ddlCreditCard.Items.IndexOf(ddlCreditCard.Items.FindByValue(txtCreditCard.Text));
        // ***************

        LoadNoOfInstallment();
    }

    private void LoadNoOfInstallment()
    {
        try
        {
            decimal _AnnualPremiumWOD = 0;
            if (!decimal.TryParse(txtFinalPrice.Text, out _AnnualPremiumWOD))
            {
                _AnnualPremiumWOD = 0;
            }

            if (_AnnualPremiumWOD < 5000 && ddlCreditCard.Text == "CHINS")
            {
                ddlNoOfInstallments.Items.Clear();
                ddlNoOfInstallments.Items.Add(new ListItem("0" + " " + Resources.CarInsurance.Installment, "0"));
            }
            else if (_AnnualPremiumWOD >= 5000 && ddlCreditCard.Text == "CHINS")
            {
                Int32 intInstallVal = 0;
                intInstallVal = CheckCommencementDateforCashInstallment();
                if (intInstallVal == 0)
                {
                    ddlNoOfInstallments.Items.Clear();
                    ddlNoOfInstallments.Items.Add(new ListItem("0" + " " + Resources.CarInsurance.Installment, "0"));
                }
                else if (intInstallVal == 2)
                {
                    ddlNoOfInstallments.Items.Clear();
                    ddlNoOfInstallments.Items.Add(new ListItem("2" + " " + Resources.CarInsurance.Installment, "2"));
                }
                else if (intInstallVal == 3)
                {
                    ddlNoOfInstallments.Items.Clear();
                    ddlNoOfInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                    ddlNoOfInstallments.Items.Add(new ListItem("2" + " " + Resources.CarInsurance.Installment, "2"));
                }
                else if (intInstallVal == 4)
                {
                    ddlNoOfInstallments.Items.Clear();
                    ddlNoOfInstallments.Items.Add(new ListItem("4" + " " + Resources.CarInsurance.Installment, "4"));
                    ddlNoOfInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                    ddlNoOfInstallments.Items.Add(new ListItem("2" + " " + Resources.CarInsurance.Installment, "2"));
                }
            }
            else if (_AnnualPremiumWOD >= 15000 && ddlCreditCard.Text == "KBANK")
            {
                if (ddlNoOfInstallments.Text == "3")
                {
                    ddlNoOfInstallments.Items.Clear();
                    ddlNoOfInstallments.Items.Add(new ListItem("10" + " " + Resources.CarInsurance.Installment, "10"));
                    ddlNoOfInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                    ddlNoOfInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                    ddlNoOfInstallments.SelectedIndex = ddlNoOfInstallments.Items.IndexOf(ddlNoOfInstallments.Items.FindByValue("3"));
                }
                else
                {
                    ddlNoOfInstallments.Items.Clear();
                    ddlNoOfInstallments.Items.Add(new ListItem("10" + " " + Resources.CarInsurance.Installment, "10"));
                    ddlNoOfInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                    ddlNoOfInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                }
            }
            else if (_AnnualPremiumWOD >= 10000 && ddlCreditCard.Text == "KBANK")
            {
                if (txtProviderId.Text == "32")
                {
                    if (txtCoverTypeId.Text == "10" || txtCoverTypeId.Text == "11" || txtCoverTypeId.Text == "21")
                    {
                        if (ddlNoOfInstallments.Text == "3")
                        {
                            ddlNoOfInstallments.Items.Clear();
                            ddlNoOfInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                            ddlNoOfInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                            ddlNoOfInstallments.SelectedIndex = ddlNoOfInstallments.Items.IndexOf(ddlNoOfInstallments.Items.FindByValue("3"));
                        }
                        else
                        {
                            ddlNoOfInstallments.Items.Clear();
                            ddlNoOfInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                            ddlNoOfInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                        }
                    }
                    else
                    {
                        ddlNoOfInstallments.Items.Clear();
                        ddlNoOfInstallments.Items.Add(new ListItem("0" + " " + Resources.CarInsurance.Installment, "0"));
                    }
                }
                else
                {
                    if (ddlNoOfInstallments.Text == "3")
                    {
                        ddlNoOfInstallments.Items.Clear();
                        ddlNoOfInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                        ddlNoOfInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                        ddlNoOfInstallments.SelectedIndex = ddlNoOfInstallments.Items.IndexOf(ddlNoOfInstallments.Items.FindByValue("3"));
                    }
                    else
                    {
                        ddlNoOfInstallments.Items.Clear();
                        ddlNoOfInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                        ddlNoOfInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                    }
                }
            }
            else
            {
                if (txtProviderId.Text == "11")
                {
                    if (ddlCreditCard.Text == "CITI")
                    {
                        ddlNoOfInstallments.Items.Clear();
                        ddlNoOfInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                    }
                    else if (ddlCreditCard.Text == "KBANK")
                    {
                        ddlNoOfInstallments.Items.Clear();
                        ddlNoOfInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                    }
                    else
                    {
                        string selectedIndex = ddlNoOfInstallments.Text;
                        ddlNoOfInstallments.Items.Clear();
                        ddlNoOfInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                        ddlNoOfInstallments.Items.Add(new ListItem("4" + " " + Resources.CarInsurance.Installment, "4"));
                        ddlNoOfInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                        ddlNoOfInstallments.SelectedIndex = ddlNoOfInstallments.Items.IndexOf(ddlNoOfInstallments.Items.FindByValue(selectedIndex));
                    }
                }
                else if (txtProviderId.Text == "29")
                {
                    if (ddlCreditCard.Text == "KBANK")
                    {
                        ddlNoOfInstallments.Items.Clear();
                        ddlNoOfInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                    }
                    else if (ddlNoOfInstallments.Text == "6")
                    {
                        ddlNoOfInstallments.Items.Clear();
                        ddlNoOfInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                        ddlNoOfInstallments.Items.Add(new ListItem("4" + " " + Resources.CarInsurance.Installment, "4"));
                    }
                    else
                    {
                        ddlNoOfInstallments.Items.Clear();
                        ddlNoOfInstallments.Items.Add(new ListItem("4" + " " + Resources.CarInsurance.Installment, "4"));
                        ddlNoOfInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                    }
                }
                else if (txtProviderId.Text == "32")
                {
                    if (txtCoverTypeId.Text == "10" || txtCoverTypeId.Text == "11" || txtCoverTypeId.Text == "21")
                    {

                        if (ddlCreditCard.Text == "KBANK")
                        {
                            ddlNoOfInstallments.Items.Clear();
                            ddlNoOfInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                        }
                        else
                        {
                            ddlNoOfInstallments.Items.Clear();
                            ddlNoOfInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                        }
                    }
                    else
                    {
                        ddlNoOfInstallments.Items.Clear();
                        ddlNoOfInstallments.Items.Add(new ListItem("0" + " " + Resources.CarInsurance.Installment, "0"));
                    }
                }
                else
                {
                    ddlNoOfInstallments.Items.Clear();
                    ddlNoOfInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                }
            }

            ddlNoOfInstallments.SelectedIndex = ddlNoOfInstallments.Items.IndexOf(ddlNoOfInstallments.Items.FindByValue(txtNoOfInstallment.Text));
        }
        catch (Exception Ex)
        {
        }
    }

    protected void ddlCreditCard_SelectedIndexChanged(object sender, EventArgs e)
    {
        LoadNoOfInstallment();
        InstallmentsCalculation();
    }

    private Int32 CheckCommencementDateforCashInstallment()
    {
        try
        {
            TimeSpan ts;
            Int32 days = 0;
            Int32 Installment = 0;
            DateTime _dtCoverCommDate = dateTimeNow;
            if (DateTime.TryParse(txtCoverageDate.Text, out _dtCoverCommDate))
            {
                DateTime _dtNow = new DateTime(dateTimeNow.Year, dateTimeNow.Month, dateTimeNow.Day);

                ts = (_dtCoverCommDate.Date - _dtNow.Date);
                days = ts.Days;

                //Start 19 Jan 2015
                if (int.Parse(dateTimeNow.ToString("yyyyMMdd")) >= 20150119)
                {
                    if (days < 60)
                    {
                        Installment = 2;
                    }
                    else if (days >= 60 && days <= 90)
                    {
                        Installment = 3;
                    }
                    else if (days > 90)
                    {
                        Installment = 4;
                    }
                    else
                    {
                        Installment = 0;
                    }
                }
                else
                {
                    if (days > 30 && days <= 60)
                    {
                        Installment = 2;
                    }
                    else if (days > 60 && days <= 90)
                    {
                        Installment = 3;
                    }
                    else if (days > 90)
                    {
                        Installment = 4;
                    }
                    else
                    {
                        Installment = 0;
                    }
                }
            }
            else
            {
                Installment = 0;
            }
            return Installment;
        }
        catch (Exception ex)
        {
            return 0;
        }
    }

    private void InstallmentsCalculation()
    {
        decimal _FinalApprovedPrice = 0;
        decimal _InstallmentAmount = 0;
        decimal _1stInstallment = 0;
        decimal _LastInstallment = 0;
        if (txtFinalPrice.Text.Trim() != "0")
        {
            if (!decimal.TryParse(txtFinalPrice.Text.Trim(), out _FinalApprovedPrice))
            {
                _FinalApprovedPrice = 0;
            }
        }

       Int32 _Installments = Convert.ToInt32(ddlNoOfInstallments.Text);
       if (_Installments <= 0)
           return;

       Int32 _Install = _Installments - 1;
        if (ddlIssuingBank.Text != "CHINS")
        {
            _InstallmentAmount = Math.Ceiling(Convert.ToDecimal(_FinalApprovedPrice / _Installments));
            _1stInstallment = Convert.ToDecimal(_InstallmentAmount * _Install);
            _LastInstallment = Convert.ToDecimal(_FinalApprovedPrice - _1stInstallment);

            lblAmountwithInterest.Text = _FinalApprovedPrice.ToString("#.00");
            lblInstallmentList.Text = _InstallmentAmount.ToString("#.00");
            lblLastInstallment.Text = _LastInstallment.ToString("#.00");

            lblAmountwithInterestTitle.Text = Resources.CarInsurance.TotalAmountwithInterest;
            lblInstallmentListTitle.Text = "1 " + Resources.CarInsurance.To + " " + _Install.ToString() + " " + Resources.CarInsurance.Months;
            lblLastInstallmentTitle.Text = Resources.CarInsurance.LastMonthInstallment;
        }
        else
        {
            decimal tempInstall = 0;
            if (_Installments == 2)
            {
                tempInstall = Convert.ToDecimal(_FinalApprovedPrice / 10);
                _LastInstallment = Math.Ceiling(Convert.ToDecimal(tempInstall * 5));
                _1stInstallment = (_FinalApprovedPrice - _LastInstallment);
            }
            else if (_Installments == 3)
            {
                tempInstall = Convert.ToDecimal(_FinalApprovedPrice / 10);
                _LastInstallment = Math.Ceiling(Convert.ToDecimal(tempInstall * 3));
                _1stInstallment = (_FinalApprovedPrice - (_LastInstallment * 2));
            }
            else if (_Installments == 4)
            {
                tempInstall = Convert.ToDecimal(_FinalApprovedPrice / 4);
                _LastInstallment = Math.Ceiling(tempInstall);
                _1stInstallment = (_FinalApprovedPrice - (_LastInstallment * 3));
            }

            lblAmountwithInterest.Text = _FinalApprovedPrice.ToString("#.00");
            lblInstallmentList.Text = _1stInstallment.ToString("#.00");
            lblLastInstallment.Text = _LastInstallment.ToString("#.00");

            lblAmountwithInterestTitle.Text = Resources.CarInsurance.TotalAmountwithInterest;
            lblInstallmentListTitle.Text = "1st " + Resources.CarInsurance.Month;
            if (_Install <= 1)
            {
                lblLastInstallmentTitle.Text = Resources.CarInsurance.LastMonthInstallment;
            }
            else
            {
                lblLastInstallmentTitle.Text = "Last " + _Install + " " + Resources.CarInsurance.Months;
            }
        }
    }

    protected void ddlNoOfInstallments_SelectedIndexChanged(object sender, EventArgs e)
    {
        InstallmentsCalculation();
        //if (ddlNoOfInstallments.Text != "-1")
        //{
        //    pnlAmountwithInterest.Visible = true;
        //}
        //else
        //{
        //    pnlAmountwithInterest.Visible = false;
        //}
    }

    protected void btnOnlinePaySubmit_Click(object sender, EventArgs e)
    {
        lblPayError.Text = "";
        lblOnlinePayError.Text = "";
        Page.Validate("olpay");
        if (txtOnlineApproveStatus.Text != string.Empty && txtOnlineApproveStatus.Text == "1")
        {
            lblPayError.Text = Resources.General.AlreadyApproved;// "Already Approved";
            lblLoadMessage.Text = string.Empty;
            return;
        }
        lblLoadMessage.Text = string.Empty;
        if (Page.IsValid)
        {
            if (Session[CE.Global.General.UserRole] != null && Session[CE.Global.General.UserRole].ToString() == "300")
            {
               
                Int16 _Valid = 1;
                if (_Valid == 1)
                {
                    Int64 _result = -1;

                    Payments _payments = new Payments();
                    PaymentsDB _paymentsdb = new PaymentsDB();
                    txtPaymentId.Text = "0";
                    _payments.PaymentId = Convert.ToInt64(txtPaymentId.Text.Trim());
                    _payments.QuoteRefNo = lblPRefNo.Text;
                    _payments.CECarId = Convert.ToInt64(txtCarId.Text);
                    _payments.ProviderCompanyId = Convert.ToInt64(txtProviderId.Text.Trim());
                    _payments.RefCEUserId = Convert.ToInt64(txtUserId.Text);
                    _payments.AgentId = Convert.ToInt64(Session[General.UserId].ToString());
                    _payments.AdminId = Convert.ToInt64(Session[General.UserId].ToString());

                    _payments.CollectedAmount = Convert.ToSingle(txtOnlineAmount.Text);

                    _payments.TransactionType = 1;
                    _payments.PaymentOption = "FP";
                    if (txtOnlinePaymentType.Text.Trim().ToUpper() == "CREDITCARD")
                    {
                        _payments.PaymentType = "CCOL";
                        _payments.CardHolder = "XXXXXXXX";
                        _payments.IssuingBank = "BBL";
                        _payments.CreditCardNo = "XXXXXXXXXXXXXXXX";
                        _payments.CVV = "XXX";
                        _payments.CardExpiryMonth = "00";
                        _payments.CardExpiryYear = "0000";
                        _payments.CardType = " ";
                    }
                    else if (txtOnlinePaymentType.Text.Trim().ToUpper() == "BANKTRANSFER")
                    {
                        _payments.PaymentType = "BKTR";
                    }
                    //else if (txtOnlinePaymentType.Text.Trim().ToUpper() == "SEVEN")
                    //{
                    //    _payments.PaymentType = "SVEV";
                    //}
                    else if (txtOnlinePaymentType.Text.Trim().ToUpper() == "FAMT")
                    {
                        _payments.PaymentType = "FAMT";
                    }
                    else if (txtOnlinePaymentType.Text.Trim().ToUpper() == "TESCO")
                    {
                        _payments.PaymentType = "TESC";
                    }
                    else if (txtOnlinePaymentType.Text.Trim().ToUpper() == "TRUEMONEY")
                    {
                        _payments.PaymentType = "TUMY";
                    }

                    _payments.ApproveType = 1;
                    _payments.PaymentRefNo = Server.HtmlEncode(txtOnlinePaymentRefNo.Text);
                    _payments.IsOnlinePayment = 1;
                    _payments.Status = true;
                    _result = _paymentsdb.Insert(_payments);
                    if (_result > 0)
                    {

                        string AgentEmail = "";
                        string strSql = "";
                        MyDatabase _db = new MyDatabase();
                        strSql = "SELECT UC.Info1 SMPTKey FROM tblCEContact UC INNER JOIN tblPayments PY ON PY.AgentId = UC.RefCEUserId WHERE PY.PaymentId  = " + txtPaymentId.Text;
                        DataTable _dtAgentId = _db.GetDataTable(strSql);
                        if (_dtAgentId != null && _dtAgentId.Rows.Count > 0)
                        {
                            string SMTPKey = _dtAgentId.Rows[0]["SMPTKey"].ToString();
                           
                            AgentEmail = GetSMTPAccount(SMTPKey.ToLower());
                        }
                        SendApproveMailToAdmin(_payments.TransactionType, txtCustomerName.Text, txtOnlineAmount.Text, AgentEmail, 1);


                        grvPayment.Enabled = true;
                        txtPaymentId.Text = "0";
                        pnlPaymentInput.Visible = true;
                        btnOnlinePaySubmit.Visible = false;
                        btnOnlinePayDecline.Visible = false;

                        lblOnlinePayError.Text = Resources.General.OnlinePaymentApprove;
                        
                        ClearPayFields();
                        DataSet _dsPayment = new DataSet();
                        _dsPayment = GetBrokerPremium();
                        if (_dsPayment != null && _dsPayment.Tables.Count > 1 && _dsPayment.Tables[1].Rows.Count > 0)
                        {
                            lblPaymentMode.Text = "";
                            if (_dsPayment.Tables[0].Rows[0]["PaymentMode"] != DBNull.Value)
                            {
                                if (_dsPayment.Tables[0].Rows[0]["PaymentMode"].ToString() == "CR")
                                    lblPaymentMode.Text = "Credit Card";
                                else if (_dsPayment.Tables[0].Rows[0]["PaymentMode"].ToString() == "TR")
                                    lblPaymentMode.Text = "โอนเงิน";
                            }

                            txtAgentComments.Text = "";
                            if (_dsPayment.Tables.Count > 0 && _dsPayment.Tables[0].Rows.Count > 0)
                            {
                                if (_dsPayment.Tables[0].Rows[0]["Info8"] != DBNull.Value && _dsPayment.Tables[0].Rows[0]["Info8"].ToString() != string.Empty)
                                {
                                    txtAgentComments.Text = _dsPayment.Tables[0].Rows[0]["Info8"].ToString();
                                }
                            }
                            txtBalanceAmount.Text = "0";
                            lblPayBalance.Text = "0";
                            txtTotalCollectedAmount.Text = "0";
                            txtTotalRefundAmount.Text = "0";
                            grvPayment.DataSource = _dsPayment.Tables[1];
                            grvPayment.DataBind();
                            txtPaymentId.Text = "0";
                            EnableDisable();
                            if (grvPayment.Rows.Count > 0)
                            {
                                btnPaymentApproval.Enabled = true;
                                chkRefund.Enabled = true;
                                DataSet _dsPaymentAmount = new DataSet();
                                _dsPaymentAmount = GetPaymentAmounts();
                                if (_dsPaymentAmount != null && _dsPaymentAmount.Tables.Count > 0 && _dsPaymentAmount.Tables[0].Rows.Count > 0)
                                {
                                    

                                    txtTotalCollectedAmount.Text = _dsPaymentAmount.Tables[0].Rows[0]["CollectedAmount"].ToString();
                                    txtTotalRefundAmount.Text = _dsPaymentAmount.Tables[0].Rows[0]["RefundAmount"].ToString();
                                }
                                divPayList.Visible = true;
                                
                            }
                            else
                            {
                                divPayList.Visible = false;
                                grvPayment.DataSource = null;
                                grvPayment.DataBind();
                            }
                        }
                        if (txtPaymentId.Text == "0")
                        {
                            chkRefund.Enabled = true;
                        }
                        else
                        {
                            chkRefund.Enabled = false;
                        }
                        ShowTescoAmount();
                    }
                }
                else
                {
                    if (_Valid == 4)
                        lblOnlinePayError.Text = Resources.General.AmountExceedBalance;
                }
            }
            else
            {
                lblOnlinePayError.Text = Resources.Proposal.AccessDenied;
            }
        }
    }

    protected void btnOnlinePayDecline_Click(object sender, EventArgs e)
    {
        Int64 _result = -1;
        Int64 CECarId = Convert.ToInt64(txtCarId.Text);
        Int64 ProviderId = Convert.ToInt64(txtProviderId.Text.Trim());
        Int64 AgentId = Convert.ToInt64(Session[General.UserId].ToString());

        NonGGPackageDB _nonggpackagedb = new NonGGPackageDB();
        if (txtAppStatus.Text == "ONLINE")
        {
            _result = _nonggpackagedb.DeclineOnlinePayment(CECarId, ProviderId, AgentId);
        }
        else if (txtAppStatus.Text == "OFFLINE")
        {
            _result = _nonggpackagedb.DeclineNonGGOnlinePayment(CECarId, ProviderId, AgentId);
        }

        if (_result > 0)
        {

            string AgentEmail = "";
            string strSql = "";
            MyDatabase _db = new MyDatabase();
            strSql = "SELECT UC.Info1 SMPTKey FROM tblCEContact UC INNER JOIN tblPayments PY ON PY.AgentId = UC.RefCEUserId WHERE PY.PaymentId  = " + txtPaymentId.Text;
            DataTable _dtAgentId = _db.GetDataTable(strSql);
            if (_dtAgentId != null && _dtAgentId.Rows.Count > 0)
            {
                string SMTPKey = _dtAgentId.Rows[0]["SMPTKey"].ToString();
                
                AgentEmail = GetSMTPAccount(SMTPKey.ToLower());
            }
            SendApproveMailToAdmin(1, txtCustomerName.Text, txtOnlineAmount.Text, AgentEmail, 0);


            grvPayment.Enabled = true;
            txtPaymentId.Text = "0";
            pnlPaymentInput.Visible = true;
            btnOnlinePaySubmit.Visible = false;
            btnOnlinePayDecline.Visible = false;
            
            lblOnlinePayError.Text = Resources.General.OnlinePaymentDecline;
        }
    }

    protected void btnPaySubmit_Click(object sender, EventArgs e)
    {
        lblPayError.Text = "";
        ScriptManager.RegisterStartupScript(ddlOption, ddlOption.GetType(), Guid.NewGuid().ToString(), "CheckPaymentType();", true);
        Page.Validate("pay");
        if (txtApproveStatus.Text != string.Empty && txtApproveStatus.Text == "1" && txtPaymentId.Text != string.Empty && txtPaymentId.Text != "0")
        {
            lblPayError.Text = Resources.General.AlreadyApproved;// "Already Approved";
            lblLoadMessage.Text = string.Empty;
            return;
        }
        //Sakthi on 25 Sep 2012 Start
        if (txtStatus.Text != string.Empty && txtStatus.Text.ToUpper() != "TRUE" && txtPaymentId.Text != string.Empty
            && txtPaymentId.Text != "0" && chkApprove.Checked && ddlPaymentOption.Text == "IP")
        {
            lblPayError.Text = Resources.General.PayMsg_AlreadyhaveAnnualPayments;
            
            lblLoadMessage.Text = string.Empty;
            return;
        }
        if (txtCashierApproved.Text != string.Empty && txtCashierApproved.Text != "0" && chkRefund.Checked == true 
            && txtTescoAmount.Text != string.Empty && Convert.ToSingle(txtTescoAmount.Text.Trim()) > 0
            && (chkTescoCash.Checked == true || chkTescoVoucher.Checked == true))
        {
            lblPayError.Text = "This Premium can't allow to Refund";
            lblLoadMessage.Text = string.Empty;
            return;
        }
        Int16 _ValidatePaymentsSubmission = ValidatePaymentsSubmission(ddlPaymentOption.Text);
        if (_ValidatePaymentsSubmission > 0)
        {
            if (_ValidatePaymentsSubmission == 1)
            {
                lblPayError.Text = Resources.General.PayMsg_InstallmentAmountCantRefund;
            }
            else if (_ValidatePaymentsSubmission == 2)
            {
                lblPayError.Text = Resources.General.PayMsg_AlreadyhaveInstallmentPayments;
            }
            else if (_ValidatePaymentsSubmission == 3)
            {
                lblPayError.Text = Resources.General.PayMsg_AlreadyhaveAnnualPayments;
            }
            lblLoadMessage.Text = string.Empty;
            return;
        }
        //Sakthi on 25 Sep 2012 End

        if (txtAmount.Text != "")
        {
            if (Convert.ToSingle(txtAmount.Text) == 0)
            {
                lblPayError.Text = Resources.CarInsurance.Amount + " ต้องมากกว่า 0";
                return;
            }
        }

        EnablePaymentOnOff();
        lblLoadMessage.Text = string.Empty;
        if (Page.IsValid)
        {
            if (SubmitPaymentPermission())
            {
                btnPaymentApproval.Enabled = true;
                Int16 _Valid = AmountExceedValid(1);
                if (_Valid == 1)
                {
                    string paymentType = ddlPaymentType.Text;

                    Int64 _result = -1;

                    Payments _payments = new Payments();
                    PaymentsDB _paymentsdb = new PaymentsDB();

                    _payments.PaymentId = Convert.ToInt64(txtPaymentId.Text.Trim());
                    _payments.QuoteRefNo = lblPRefNo.Text;
                    _payments.CECarId = Convert.ToInt64(txtCarId.Text);
                    _payments.ProviderCompanyId = Convert.ToInt64(txtProviderId.Text.Trim());
                    _payments.RefCEUserId = Convert.ToInt64(txtUserId.Text);
                    if (_payments.PaymentId == 0)
                    {
                        _payments.AgentId = Convert.ToInt64(Session[General.UserId].ToString());
                        _payments.AdminId = 0;
                    }
                    else
                    {
                        _payments.AgentId = 0;
                        _payments.AdminId = Convert.ToInt64(Session[General.UserId].ToString());
                    }

                    _payments.CollectedAmount = Convert.ToSingle(txtAmount.Text);
                    if (chkRefund.Checked)
                    {
                        _payments.TransactionType = 2;
                    }
                    else
                    {
                        _payments.TransactionType = 1;
                        _payments.PaymentOption = ddlPaymentOption.Text;
                        if (ddlPaymentOption.Text == "IP")
                        {
                            _payments.NoofInstallments = Convert.ToInt16(ddlNoOfInstallments.Text);
                            float AmountwithInterest = 0.0f;
                            if (!float.TryParse(lblAmountwithInterest.Text, out AmountwithInterest))
                            {
                                AmountwithInterest = 0.0f;
                            }
                            _payments.AmountwithInterest = AmountwithInterest;
                        }
                        _payments.PaymentType = ddlPaymentType.Text;
                        if (ddlPaymentType.Text == "BKTR" || ddlPaymentType.Text == "CHINS")
                        {
                            _payments.PaymentBank = ddlBank.Text;
                        }
                        _payments.IssuingBank = Server.HtmlEncode(txtIssuingBank.Text);
                        _payments.CardType = ddlCardType.Text;

                        //_payments.CardHolder = Server.HtmlEncode(txtCardHolder.Text);
                        //if (_payments.PaymentId > 0)
                        //{
                        //    _payments.CreditCardNo = txtCardNo1.Text.Trim() + "XXXXXXXX" + txtCardNo4.Text.Trim();
                        //    _payments.CVV = "XXX";
                        //}
                        //else
                        //{
                        //    _payments.CreditCardNo = txtCardNo1.Text.Trim() + txtCardNo2.Text.Trim() + txtCardNo3.Text.Trim() + txtCardNo4.Text.Trim();
                        //    _payments.CVV = txtCVV.Text;
                        //}
                        // 17/07/2013 Change to textbox
                        //_payments.CardExpiryMonth = txtCardExpiryMonth.Text; //ddlCardExpiryMonth.Text;
                        //_payments.CardExpiryYear = txtCardExpiryYear.Text; //ddlCardExpiryYear.Text;
                        
                    }
                    if (chkApprove.Checked)
                    {
                        _payments.ApproveType = 1;
                    }
                    else
                    {
                        _payments.ApproveType = 0;
                    }

                    _payments.PaymentRefNo = Server.HtmlEncode(txtPaymentRefNo.Text);
                    _payments.IsOnlinePayment = 0;
                    Int32 noofdays = 0;
                    Int32 noofrecords = 0;
                    if (!Int32.TryParse(txtDays.Text, out noofdays))
                    {
                        noofdays = 0;
                    }
                    if (!Int32.TryParse(txtNoOfRecords.Text, out noofrecords))
                    {
                        noofrecords = 0;
                    }
                    _payments.Status = true;
                    _payments.NoOfDays = noofdays;
                    if (txtUserTypeId.Text != string.Empty)
                    {
                        _payments.UserTypeId = Convert.ToInt32(txtUserTypeId.Text);
                    }
                    _payments.Info2 = Server.HtmlEncode(txtAgentRemarks.Text);
                    _result = _paymentsdb.Insert(_payments);
                    string paymentId = _result.ToString();

                    if (_result > 0)
                    {
                        string _TescoSelectedId = "0";
                        if (chkTescoVoucher.Checked)
                        {
                            _TescoSelectedId = "1";
                        }
                        else if (chkTescoCash.Checked)
                        {
                            _TescoSelectedId = "2";
                        }

                        if (chkRefund.Checked == false)
                        {
                            MyDatabase _myDB = new MyDatabase();
                            string _strUpdateSQL = "UPDATE tblCXBrokerPremium SET ";
                            //*** Yui@05/01/2014 ***
                            _strUpdateSQL += " PaymentOption = '" + ddlPaymentOption.Text + "',";
                            if (ddlPaymentOption.Text == "IP")
                            {
                                _strUpdateSQL += " NoofInstallment = " + ddlNoOfInstallments.Text + ",";
                                _strUpdateSQL += " Bank = '" + ddlCreditCard.Text + "',";
                                _strUpdateSQL += " InstallmentAmountWOD = " + Convert.ToSingle(lblInstallmentList.Text) + ",";
                                _strUpdateSQL += " LastInstallmentAmountWOD = " + Convert.ToSingle(lblLastInstallment.Text) + ",";
                            }
                            //**********************
                            _strUpdateSQL += " TescoSelect = " + _TescoSelectedId + ",";
                            _strUpdateSQL += " TescoAmount = " + txtTescoAmount.Text.Trim() + ",";
                            _strUpdateSQL += " ApprovedPremium = " + txtFinalPrice.Text.Trim();
                            _strUpdateSQL += " WHERE CECarId = " + txtCarId.Text + " AND SelectedStatus = 1 AND Info1 = '" + lblUpRefNo.Text.Trim() + "'";
                            _result = _myDB.ExecuteNonSqlStatement(_strUpdateSQL);
                        }
                        else
                        {
                            //*** Yui@05/01/2014 ***
                            MyDatabase _myDB = new MyDatabase();
                            string _strUpdateSQL = "UPDATE tblCXBrokerPremium SET ";
                            _strUpdateSQL += " PaymentOption = '" + ddlPaymentOption.Text + "',";
                            if (ddlPaymentOption.Text == "IP")
                            {
                                _strUpdateSQL += " NoofInstallment = " + ddlNoOfInstallments.Text + ",";
                                _strUpdateSQL += " Bank = '" + ddlCreditCard.Text + "',";
                                _strUpdateSQL += " InstallmentAmountWOD = " + Convert.ToSingle(lblInstallmentList.Text) + ",";
                                _strUpdateSQL += " LastInstallmentAmountWOD = " + Convert.ToSingle(lblLastInstallment.Text) + ",";
                            }
                            _strUpdateSQL += " WHERE CECarId = " + txtCarId.Text + " AND SelectedStatus = 1 AND Info1 = '" + lblUpRefNo.Text.Trim() + "'";
                            _result = _myDB.ExecuteNonSqlStatement(_strUpdateSQL);
                        }

                        if (chkApprove.Checked && txtPaymentId.Text != string.Empty)
                        {
                            string AgentEmail = "";
                            string strSql = "";
                            MyDatabase _db = new MyDatabase();
                            strSql = "SELECT UC.Info1 SMPTKey FROM tblCEContact UC INNER JOIN tblPayments PY ON PY.AgentId = UC.RefCEUserId WHERE PY.PaymentId  = " + txtPaymentId.Text;
                            DataTable _dtAgentId = _db.GetDataTable(strSql);
                            if (_dtAgentId != null && _dtAgentId.Rows.Count > 0)
                            {
                                string SMTPKey = _dtAgentId.Rows[0]["SMPTKey"].ToString();
                                AgentEmail = GetSMTPAccount(SMTPKey.ToLower());
                            }
                            SendApproveMailToAdmin(_payments.TransactionType, txtCustomerName.Text, txtAmount.Text, AgentEmail, _payments.ApproveType);
                        }
                        if (Session[CE.Global.General.UserRole] != null)
                        {
                            MyDatabase _dbIsNew = new MyDatabase();
                            string strIsNew = "SELECT Info1 FROM [tblNonGGCarMoreDetails] WHERE CECarId = @CECarId And RefCEUserId = @RefCEUserId";
                            SortedList _paraIsNewList = new SortedList();
                            _paraIsNewList.Add("@CECarId", txtCarId.Text);
                            _paraIsNewList.Add("@RefCEUserId", txtUserId.Text);
                            object _retVal = _dbIsNew.ExecuteScalarSqlStatement(strIsNew, _paraIsNewList);
                            string appTypeNmae = "";

                            if (_retVal != null)
                            {
                                switch (_retVal.ToString())
                                {
                                    case "CHB":
                                        appTypeNmae = "Change Broker";
                                        break;
                                    case "NEW":
                                        appTypeNmae = "New";
                                        break;
                                    case "RNO":
                                        appTypeNmae = "Renewal with Other Insurer";
                                        break;
                                    case "REN":
                                        appTypeNmae = "Renewal";
                                        break;
                                    default:
                                        appTypeNmae = "";
                                        break;
                                }
                            }

                            //&& Session[CE.Global.General.UserRole].ToString() == "100"
                            string mailBody = "";
                            string _emailTitle = "";
                            string _toemail = "";
                            string _ccemail = "";
                            string _bccemail = "";
                            _emailTitle = "[" + lblUpRefNo.Text + "] " + Resources.CarInsurance.Payment + "  [" + txtPlateNumber.Text + "]";
                            mailBody = Resources.General.CustomerName + " : " + txtCustomerName.Text + "<br/><br/>";
                            mailBody += Resources.General.ReferenceNo + " : " + lblUpRefNo.Text + "<br/><br/>";

                            if (appTypeNmae != "")
                                mailBody += "App Type : " + appTypeNmae + "<br/><br/>";

                            mailBody += Resources.CarInsurance.PaymentType + " : " + ddlPaymentType.SelectedItem.Text + "<br/><br/>";
                            mailBody += Resources.CarInsurance.Amount + " : " + txtAmount.Text + "<br/><br/>";
                            if (_payments.TransactionType == 1)
                            {
                                mailBody += Resources.General.TransactionType + " : " + Resources.CarInsurance.Payment + "<br/><br/>";
                            }
                            else if (_payments.TransactionType == 2)
                            {
                                mailBody += Resources.General.TransactionType + " : " + Resources.CarInsurance.Refund + "<br/><br/>";
                            }

                            mailBody += Resources.General.Broker + " : " + lblAgentName.Text; //Session[CE.Global.General.UserName].ToString() + "<br/><br/>";

                            if (txtAgentComments.Text.Trim() != "")
                            {
                                mailBody += "Agent Quote Page Comments : " + txtAgentComments.Text.Trim() + "<br/><br/>";
                            }

                            _toemail = CE.Configuration.MyConfigurationManager.GetAppSettingValue("PAYMENT"); //Add 08/Jan/2014
                            /* Hide on 08/Jan/2014
                            _toemail += CE.Configuration.MyConfigurationManager.GetAppSettingValue("ADMIN");
                            _toemail += CE.Configuration.MyConfigurationManager.GetAppSettingValue("TO_ROY");
                            _toemail += CE.Configuration.MyConfigurationManager.GetAppSettingValue("SUPERVISOR"); */

                            string replyTo = "";
                            if (hidAgentEmail.Value.Trim() != "")
                            {
                                _ccemail += hidAgentEmail.Value.Trim();
                                replyTo = hidAgentEmail.Value.Trim();
                            }
                            else
                            {
                                //if (Session[General.UserRole].ToString() == "100")
                                _ccemail += Session[General.SMTPReplyTo].ToString();
                                replyTo = Session[General.SMTPReplyTo].ToString();
                            }
                            _bccemail = "";

                            MyMailManager.SendGGMail(ConfigurationManager.AppSettings["GGFormsSMTPAccount"].ToString(), ConfigurationManager.AppSettings["GGFormsSMTPAuthCode"].ToString(), _toemail, _ccemail, _bccemail, _emailTitle, mailBody, replyTo);
                        }

                        if (paymentType == "FAMT" ||
                        paymentType == "TESC" ||
                        paymentType == "TUMY")
                        {
                            //paymentType == "SVEV"
                            if (chk123Service.Checked)
                            {
                                string carID = paymentId;
                                Session["CTSVCRM123"] = postBackToMerchant(carID, paymentType);
                            }
                        }

                        ClearPayFields();
                        DataSet _dsPayment = new DataSet();
                        _dsPayment = GetBrokerPremium();
                        if (_dsPayment != null && _dsPayment.Tables.Count > 1 && _dsPayment.Tables[1].Rows.Count > 0)
                        {
                            lblPaymentMode.Text = "";
                            if (_dsPayment.Tables[0].Rows[0]["PaymentMode"] != DBNull.Value)
                            {
                                if (_dsPayment.Tables[0].Rows[0]["PaymentMode"].ToString() == "CR")
                                    lblPaymentMode.Text = "Credit Card";
                                else if (_dsPayment.Tables[0].Rows[0]["PaymentMode"].ToString() == "TR")
                                    lblPaymentMode.Text = "โอนเงิน";
                            }

                            txtAgentComments.Text = "";
                            if (_dsPayment.Tables.Count > 0 && _dsPayment.Tables[0].Rows.Count > 0)
                            {
                                if (_dsPayment.Tables[0].Rows[0]["Info8"] != DBNull.Value && _dsPayment.Tables[0].Rows[0]["Info8"].ToString() != string.Empty)
                                {
                                    txtAgentComments.Text = _dsPayment.Tables[0].Rows[0]["Info8"].ToString();
                                }
                            }
                            txtBalanceAmount.Text = "0";
                            lblPayBalance.Text = "0";
                            txtTotalCollectedAmount.Text = "0";
                            txtTotalRefundAmount.Text = "0";
                            grvPayment.DataSource = _dsPayment.Tables[1];
                            grvPayment.DataBind();
                            txtPaymentId.Text = "0";
                            EnableDisable();
                            if (grvPayment.Rows.Count > 0)
                            {
                                btnPaymentApproval.Enabled = true;
                                chkRefund.Enabled = true;
                                DataSet _dsPaymentAmount = new DataSet();
                                _dsPaymentAmount = GetPaymentAmounts();
                                if (_dsPaymentAmount != null && _dsPaymentAmount.Tables.Count > 0 && _dsPaymentAmount.Tables[0].Rows.Count > 0)
                                {

                                    txtTotalCollectedAmount.Text = _dsPaymentAmount.Tables[0].Rows[0]["CollectedAmount"].ToString();
                                    txtTotalRefundAmount.Text = _dsPaymentAmount.Tables[0].Rows[0]["RefundAmount"].ToString();
                                }
                                divPayList.Visible = true;


                            }
                            else
                            {
                                divPayList.Visible = false;
                                grvPayment.DataSource = null;
                                grvPayment.DataBind();
                            }
                        }
                        if (txtPaymentId.Text == "0")
                        {
                            chkRefund.Enabled = true;
                        }
                        else
                        {
                            chkRefund.Enabled = false;
                        }
                        ShowTescoAmount();
                    }

                    if (paymentType == "FAMT" ||
                        paymentType == "TESC" ||
                        paymentType == "TUMY")
                    {
                        //paymentType == "SVEV"
                        if (chk123Service.Checked)
                        {
                            //string carID = paymentId; //Session[CE.Global.General.CarId].ToString();
                            //string userEmail = Session[General.UserEmail].ToString();
                            //General.ClearAllSession(this.Page, "ALL");
                            //Session["CTSVCRM123"] = postBackToMerchant(carID, paymentType);
                            string _redirectUrl = "../counterservice/counterservice.aspx";
                            //Session["CTSVMSG"] = Session[General.ProviderCompanyId].ToString() + "," + _refid;
                            //Response.Redirect(_redirectUrl);

                            ScriptManager.RegisterStartupScript(Page, typeof(Page), "OpenWindow", "window.open('" + _redirectUrl + "');", true);
                            //ScriptManager.RegisterStartupScript(this, typeof(string), "New_Window", "window.open( 'http://www.website.com', null, 'height=800,width=1280,status=yes,toolbar=yes,menubar=yes,location=no' );", true);
                        }
                    }
                }
                else
                {
                    if (_Valid == 2)
                        lblPayError.Text = Resources.CarInsurance.ExceedCollected;
                    else if (_Valid == 3)
                        lblPayError.Text = Resources.CarInsurance.ExceedPremium;
                }
            }
            else
            {
                lblPayError.Text = Resources.Proposal.AccessDenied;
            }
        }
    }

    private string insertCounterService(string paymentId, string QRefNo, string userEmail)
    {
        MyDatabase _db = new MyDatabase();
        SortedList _sPara = new SortedList();
        _sPara.Add("@IsGGWeb", false);
        _sPara.Add("@CarId", txtCarId.Text);
        _sPara.Add("@RefId", paymentId);
        _sPara.Add("@RefNo", QRefNo);
        _sPara.Add("@UserEmail", userEmail);
        object rtnVal = _db.ExecuteSP("sprocCounterServiceInsertSingleItem", _sPara);
        if (rtnVal != null)
        {
            if (rtnVal.ToString() != "-1")
            {
                return rtnVal.ToString();
            }
        }
        return paymentId;
    }

    //<asp:ListItem Value="SVEV" Text="<%$ Resources:CarInsurance,SevenEleven%>"></asp:ListItem>
    private string postBackToMerchant(string paymentID, string paymentType)
    {
        int expDate = 0;
        DateTime dteToday = new DateTime(General.GetUTCDateTime().Year, General.GetUTCDateTime().Month, General.GetUTCDateTime().Day, 23, 0, 0);

        Int64 CECarId = Convert.ToInt64(txtCarId.Text);
        Int64 ProviderId = Convert.ToInt64(txtProviderId.Text.Trim());
        DataSet _dsApplication = new DataSet();
        NonGGPackageDB _nonggpackagedb = new NonGGPackageDB();
        _dsApplication = _nonggpackagedb.GetNonGGApplication(CECarId, ProviderId, 0);
      
        if (_dsApplication.Tables[0].Rows.Count > 0)
        {
            string[] splitDate = _dsApplication.Tables[0].Rows[0]["CommencementDate"].ToString().Split(' ');
            if (splitDate.Length == 3)
            {
                int yer = 0;
                string[] mth;
                mth = new string[12] { "jan", "feb", "mar", "apr",
                               "may", "jun", "jul", "aug",
                               "sep", "oct", "nov", "dec"};
                yer = int.Parse(splitDate[2]);

                int cMth = 0;
                for (int m = 0; m < 12; m++)
                {
                    if (splitDate[1].ToLower() == mth[m])
                    {
                        cMth = m + 1;
                        break;
                    }
                }

                DateTime dteExp = new DateTime(yer, cMth, int.Parse(splitDate[0]), 23, 0, 0);
                double dateDiff = (dteExp.Date - dteToday).TotalDays;

                if (dateDiff >= 7)
                {
                    expDate = 7;
                }
                else
                {
                    expDate = Convert.ToInt32(dateDiff);
                    if (expDate < 0) expDate = 0;
                }
            }

            string Email = _dsApplication.Tables[0].Rows[0]["Email"].ToString();
            string Name = _dsApplication.Tables[0].Rows[0]["Name"].ToString();
            string Insurer = _dsApplication.Tables[0].Rows[0]["CompanyName"].ToString();
            string Package = _dsApplication.Tables[0].Rows[0]["Package"].ToString();
            string QuoteRefNo = _dsApplication.Tables[0].Rows[0]["QuoteRefNo"].ToString();
            string ContactNo = _dsApplication.Tables[0].Rows[0]["ContactNo"].ToString();

            string csId = insertCounterService(paymentID, QuoteRefNo, Email);

            //MerchantID+InvoiceNo+Amount
            //InvoiceNo = Convert.ToInt64(Session[General.CarId].ToString())
            string totalprice = "";
            if (!txtAmount.Text.Trim().Contains("."))
            {
                txtAmount.Text += ".00";
            }
            totalprice = txtAmount.Text.Replace(Resources.CarInsurance.Baht, "").Trim().Replace(",", "").Replace(".", "").PadLeft(12, '0');
            
            string hashVal = "256" + csId + totalprice; //merchant@gluaygluay.com , carID
            hash_hmac_sha1 hash = new hash_hmac_sha1();

            StringBuilder sendXml = new StringBuilder();
            sendXml.Append("<OneTwoThreeReq>");
            sendXml.Append("<Version>1.1</Version>");
            sendXml.Append("<TimeStamp>" + General.GetUTCDateTime().ToString("yyyy-MM-dd HH:mm:ss:fff", new System.Globalization.CultureInfo("en-US")) + "</TimeStamp>"); //2014-01-09 11:50:12:888
            sendXml.Append("<MessageID>" + QuoteRefNo + "</MessageID>");
            sendXml.Append("<MerchantID>256</MerchantID>"); //merchant@gluaygluay.com
            sendXml.Append("<InvoiceNo>" + csId + "</InvoiceNo>"); //carID
            sendXml.Append("<Amount>" + totalprice + "</Amount>");
            sendXml.Append("<Discount>000000000000</Discount>");
            sendXml.Append("<ServiceFee>000000000000</ServiceFee>");
            sendXml.Append("<ShippingFee>000000000000</ShippingFee>");
            sendXml.Append("<CurrencyCode>THB</CurrencyCode>");
            sendXml.Append("<CountryCode>THA</CountryCode>");
            sendXml.Append("<ProductDesc>" + Insurer + "</ProductDesc>");
            sendXml.Append("<PaymentItems>");
            sendXml.Append("<PaymentItem id=\"1\" name=\"" + Package + "\" price=\"" + totalprice + "\" quantity=\"1\" />");
            sendXml.Append("</PaymentItems>");
            sendXml.Append("<PayerName>" + Name + "</PayerName>");
            sendXml.Append("<PayerEmail>" + Email + "</PayerEmail>");
            sendXml.Append("<PayerMobile>" + ContactNo + "</PayerMobile>");
            sendXml.Append("<ShippingAddress>Bangkok</ShippingAddress>");
            sendXml.Append("<MerchantUrl>" + ConfigurationManager.AppSettings["Service123Return"].ToString() + "</MerchantUrl>"); //the payer clicked on GoBackMerchant button at 1-2-3 result page //http://test.gluaygluay.com.gluaygluay.info.bluebell.arvixe.com/car-insurance/counterservice/counterservicemessage.aspx
            sendXml.Append("<APICallUrl></APICallUrl>"); //after payment is PAID or PENDING

            //if (paymentType == "SVEV")
            //{
            //    sendXml.Append("<AgentCode>7ELEVEN</AgentCode>");
            //}
            if (paymentType == "FAMT")
            {
                sendXml.Append("<AgentCode>FAMILYMART</AgentCode>");
            }
            else if (paymentType == "TESC")
            {
                sendXml.Append("<AgentCode>TESCO</AgentCode>");
            }
            else if (paymentType == "TUMY")
            {
                sendXml.Append("<AgentCode>TRUEMONEY</AgentCode>");
            }
            //7ELEVEN= 7 Eleven Counter Service
            //TRUEMONEY= True Money Shop
            //TESCO= Tesco Lotus Counter Service
            sendXml.Append("<ChannelCode>OVERTHECOUNTER</ChannelCode>");
            if (lblLangOption.Text != "1")
            {
                sendXml.Append("<PayInSlipInfo>If you need any helps, please call our contact#|Tel.: 02-268-8222 or Email: support@gluaygluay.com|GG Ref.#: " + QuoteRefNo + "</PayInSlipInfo>"); //If your purchase amount is less than 2000 Baht, you have to pay 59 Baht as convenience fee.| Our hot promotions are iPhone5, Galaxy S3. | 
            }
            else
            {
                sendXml.Append("<PayInSlipInfo>หากต้องการความช่วยเหลือโปรดติดต่อหาเราที่|เบอร์: 02-268-8222 หรืออีเมล์: support@gluaygluay.com|หมายเลขอ้างอิง: " + QuoteRefNo + "</PayInSlipInfo>");
            }
            sendXml.Append("<PaymentExpiry>" + dteToday.AddDays(expDate).ToString("yyyy-MM-dd HH:mm:ss", new System.Globalization.CultureInfo("en-US")) + "</PaymentExpiry>");
            sendXml.Append("<UserDefined1></UserDefined1>");
            sendXml.Append("<UserDefined2></UserDefined2>");
            sendXml.Append("<UserDefined3></UserDefined3>");
            sendXml.Append("<UserDefined4></UserDefined4>");
            sendXml.Append("<UserDefined5></UserDefined5>");
            sendXml.Append("<HashValue>" + hash.getHMAC(hashVal, "5G7JL5J3RTZ0V2BW32R3TQ3953Q040R5") + "</HashValue>"); //UXF8LF0M9L8LWB4WXTGO46GOK4YSUQDC
            sendXml.Append("</OneTwoThreeReq>");

            SinaptIQPKCS7.PKCS7 pkcs7 = new SinaptIQPKCS7.PKCS7();

            string base64Str = pkcs7.encryptMessage(sendXml.ToString(), pkcs7.getPublicCert(Request.PhysicalApplicationPath + @"\App_Code\counterservice\123Public.cer"));

            StringBuilder sb = new StringBuilder();
            sb.Append("<html><head><title>GluayGluay (123 Service)</title></head>");
            sb.Append("<body>");
            sb.Append("<form name=\"PostForm\" id=\"PostForm\" action=\"https://secure.123.co.th/Payment/paywith123.aspx\" method=\"post\">"); //http://uat.123.co.th/payment/paywith123.aspx
            sb.Append("<input type=\"hidden\" name=\"OneTwoThreeReq\" value=\"" + base64Str + "\" />");
            sb.Append("<input type=\"submit\" value=\"\" name=\"submit\" style=\"width:0px\" />");
            sb.Append("<script language=\"JavaScript\" type=\"text/javascript\">");
            sb.Append("window.onload = function()");
            sb.Append("{");
            sb.Append("document.PostForm.submit.click();");
            sb.Append("}");
            sb.Append("</script>");
            sb.Append("</form></body></html>");

            return sb.ToString();
        }

        return "";
    }

    protected void btnPayDecline_Click(object sender, EventArgs e)
    {
        if (txtCarId.Text != string.Empty && txtPaymentId.Text != string.Empty)
        {
            if (txtStatus.Text != string.Empty && txtStatus.Text.ToUpper() != "TRUE" && txtPaymentId.Text != string.Empty && txtPaymentId.Text != "0")
            {
                lblPayError.Text = Resources.General.AlreadyDeclined;// "Already Declined";
                lblLoadMessage.Text = string.Empty;
                return;
            }
            if (Session[CE.Global.General.UserRole] != null && Session[CE.Global.General.UserRole].ToString() == "300")
            {
                Int64 _result = -1;
                Int64 CECarId = Convert.ToInt64(txtCarId.Text);
                Int64 AdminId = Convert.ToInt64(Session[General.UserId].ToString());
                Int64 PaymentId = Convert.ToInt64(txtPaymentId.Text);

                NonGGPackageDB _nonggpackagedb = new NonGGPackageDB();
                _result = _nonggpackagedb.DeclineNonGGPayment(CECarId, AdminId, PaymentId);

                if (_result > 0)
                {
                    if (txtPaymentId.Text != string.Empty)
                    {
                        Int16 TransactionType = 0;
                        if (chkRefund.Checked)
                        {
                            TransactionType = 2;
                        }
                        else
                        {
                            TransactionType = 1;
                        }
                        string AgentEmail = "";
                        string strSql = "";
                        MyDatabase _db = new MyDatabase();
                        strSql = "SELECT UC.Info1 SMPTKey FROM tblCEContact UC INNER JOIN tblPayments PY ON PY.AgentId = UC.RefCEUserId WHERE PY.PaymentId  = " + txtPaymentId.Text;
                        DataTable _dtAgentId = _db.GetDataTable(strSql);
                        if (_dtAgentId != null && _dtAgentId.Rows.Count > 0)
                        {
                            string SMTPKey = _dtAgentId.Rows[0]["SMPTKey"].ToString();

                           
                            AgentEmail = GetSMTPAccount(SMTPKey.ToLower());
                        }
                        SendApproveMailToAdmin(TransactionType, txtCustomerName.Text, txtAmount.Text, AgentEmail, 0);
                    }

                    ClearPayFields();
                    DataSet _dsPayment = new DataSet();
                    _dsPayment = GetBrokerPremium();
                    if (_dsPayment != null && _dsPayment.Tables.Count > 1 && _dsPayment.Tables[1].Rows.Count > 0)
                    {
                        lblPaymentMode.Text = "";
                        if (_dsPayment.Tables[0].Rows[0]["PaymentMode"] != DBNull.Value)
                        {
                            if (_dsPayment.Tables[0].Rows[0]["PaymentMode"].ToString() == "CR")
                                lblPaymentMode.Text = "Credit Card";
                            else if (_dsPayment.Tables[0].Rows[0]["PaymentMode"].ToString() == "TR")
                                lblPaymentMode.Text = "โอนเงิน";
                        }

                        txtAgentComments.Text = "";
                        if (_dsPayment.Tables.Count > 0 && _dsPayment.Tables[0].Rows.Count > 0)
                        {
                            if (_dsPayment.Tables[0].Rows[0]["Info8"] != DBNull.Value && _dsPayment.Tables[0].Rows[0]["Info8"].ToString() != string.Empty)
                            {
                                txtAgentComments.Text = _dsPayment.Tables[0].Rows[0]["Info8"].ToString();
                            }
                        }
                        txtBalanceAmount.Text = "0";
                        lblPayBalance.Text = "0";
                        txtTotalCollectedAmount.Text = "0";
                        txtTotalRefundAmount.Text = "0";
                        grvPayment.DataSource = _dsPayment.Tables[1];
                        grvPayment.DataBind();
                        txtPaymentId.Text = "0";
                        EnableDisable();
                        if (grvPayment.Rows.Count > 0)
                        {
                            btnPaymentApproval.Enabled = true;
                            chkRefund.Enabled = true;
                            DataSet _dsPaymentAmount = new DataSet();
                            _dsPaymentAmount = GetPaymentAmounts();
                            if (_dsPaymentAmount != null && _dsPaymentAmount.Tables.Count > 0 && _dsPaymentAmount.Tables[0].Rows.Count > 0)
                            {
                                
                                txtTotalCollectedAmount.Text = _dsPaymentAmount.Tables[0].Rows[0]["CollectedAmount"].ToString();
                                txtTotalRefundAmount.Text = _dsPaymentAmount.Tables[0].Rows[0]["RefundAmount"].ToString();
                            }
                            divPayList.Visible = true;
                        
                            
                        }
                        else
                        {
                            divPayList.Visible = false;
                            grvPayment.DataSource = null;
                            grvPayment.DataBind();
                           
                        }
                    }
                    if (txtPaymentId.Text == "0")
                    {
                        chkRefund.Enabled = true;
                    }
                    else
                    {
                        chkRefund.Enabled = false;
                    }
                    ShowTescoAmount();
                }
            }
            else
            {
                lblPayError.Text = Resources.Proposal.AccessDenied;
            }
        }
    }

    protected void btnPayNew_Click(object sender, EventArgs e)
    {
        ClearPayFields();
       
        EnablePaymentOnOff();
    }

    protected void btnApplicationCancel_Click(object sender, EventArgs e)
    {
        txtLastQuoteRefNo.Text = lblUpRefNo.Text.Trim();
        Page.Validate("appcancel");
        if (Page.IsValid)
        {
            Int64 _result = -1;
            Int16 Step = 1;
            Int64 CECarId = Convert.ToInt64(txtCarId.Text);
            Int64 ProviderId = Convert.ToInt64(txtProviderId.Text.Trim());
            string Remarks = Server.HtmlEncode(txtRemark.Text.Trim());
            Int64 AgentId = Convert.ToInt64(Session[General.UserId].ToString());

            NonGGPackageDB _nonggpackagedb = new NonGGPackageDB();
            _result = _nonggpackagedb.UpdateApplicationCancelStatus(CECarId, ProviderId, AgentId, Step, Remarks);
            if (_result > 0)
            {
                pnlApplicationCancel.Visible = false;
               
                lblOptionMessage.Text = Resources.CarInsurance.SuccessCancelApplication;
                pnlOptionMessage.Visible = true;

                
                txtCancelStatus.Text = "1";
                ddlOption.Items.Clear();
                ddlOption.Items.Add(new ListItem(Resources.CarInsurance.Select, "0"));
                ddlOption.Items.Add(new ListItem(Resources.CarInsurance.Retrieve, "RTRV"));
                ddlOption.SelectedIndex = 0;
               
                ddlOption.SelectedIndex = 0;
                ddlOption_SelectedIndexChanged(null, null);
            }
        }
    }

    protected void btnApplicationRetrieve_Click(object sender, EventArgs e)
    {
        txtLastQuoteRefNo.Text = lblUpRefNo.Text.Trim();
       
        if (Session[CE.Global.General.UserRole] != null && Session[CE.Global.General.UserRole].ToString() != "100")
        {
            if (CheckSelectedItem(lblUpRefNo.Text.ToUpper()))
            {
                Int64 _result = -1;
                Int16 Step = 2;
                Int64 CECarId = Convert.ToInt64(txtCarId.Text);
                Int64 ProviderId = Convert.ToInt64(txtProviderId.Text.Trim());
                Int64 AgentId = Convert.ToInt64(Session[General.UserId].ToString());

                NonGGPackageDB _nonggpackagedb = new NonGGPackageDB();
                _result = _nonggpackagedb.UpdateApplicationRetrieveStatus(CECarId, ProviderId, AgentId, Step, lblUpRefNo.Text.ToUpper());
                if (_result > 0)
                {
                    pnlApplicationRetrieve.Visible = false;
                    lblOptionMessage.Text = Resources.CarInsurance.SuccessRetrieveApplication;
                    pnlOptionMessage.Visible = true;
                    
                    txtCancelStatus.Text = "0";
                    LoadOption();
                    ddlOption.SelectedIndex = 0;
                    ddlOption_SelectedIndexChanged(null, null);
                }
            }
            else
            {
                lblSearchMessage.Text = Resources.General.CheckRefNo;
            }
        }
        else
        {
            lblOptionMessage.Text = Resources.Proposal.AccessDenied;
            pnlOptionMessage.Visible = true;
        }
    }

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        Span1.InnerHtml = "";
        Page.Validate("upload");
        if (Page.IsValid)
        {
            if (FileUpLoad1.HasFile)
            {
                int DocNo = 1;
                Int64 _fileSize = 0;
                string _todaydate = dateTimeNow.ToString("ddMMMMyyyy");
                string _filePath = GetPdfFilePath("documents");
                string _IsPDF = Path.GetExtension(FileUpLoad1.FileName);
                string _OriginalFile = Path.GetFileName(FileUpLoad1.FileName);
                string _fileName = ddlFileUploadType.SelectedItem.Text + "_" + txtCarId.Text.Trim() + "_" + GetRandomNo() + "_" + _todaydate;
                _fileName = _fileName.Replace(' ', '_');
                _fileSize = FileUpLoad1.FileContent.Length;
                if (_IsPDF.ToUpper() == ".PDF")
                {
                    if ((_fileSize / 1024) < 1025)
                    {
                        try
                        {
                            FileUpLoad1.PostedFile.SaveAs(_filePath + _fileName + ".pdf");

                            Int64 _uploadResult = 0;
                           
                            string _DocRefNo = "";
                            DateTime _tDate = new DateTime();
                            _tDate = dateTimeNow;
                            _DocRefNo = _tDate.Year.ToString("0000") + _tDate.Month.ToString("00") + _tDate.Day.ToString("00") + _tDate.Hour.ToString("00") + _tDate.Minute.ToString("00") + _tDate.Second.ToString("00");
                            _DocRefNo += txtCarId.Text.Trim() + "A" + Session[General.UserId].ToString();
                            CarFileUpload _carfileupload = new CarFileUpload();
                            CarFileUploadDB _carfileuploaddb = new CarFileUploadDB();

                            _carfileupload.CarId = Convert.ToInt64(txtCarId.Text.Trim());
                            _carfileupload.ProviderCompanyId = Convert.ToInt64(txtProviderId.Text.Trim());
                            _carfileupload.InsuranceType = "CI";
                            _carfileupload.AgentId = Convert.ToInt64(Session[General.UserId].ToString());
                            _carfileupload.DocRefNo = _DocRefNo;
                            _carfileupload.DocumentNo = DocNo;
                            _carfileupload.FileTypeId = Convert.ToInt64(ddlFileUploadType.Text);
                            _carfileupload.FileName = _filePath + _fileName.ToString() + ".pdf";
                            _carfileupload.OriginalName = _OriginalFile.ToString();
                            _carfileupload.Status = true;
                            _carfileupload.TotalFiles = DocNo;
                            _uploadResult = _carfileuploaddb.InsertNonGG(_carfileupload);

                            if (_uploadResult > 0)
                            {
                               
                                txtChassisNumber.Text = "";

                                pnlOptionMessage.Visible = true;
                                lblOptionMessage.Text = Resources.General.SuccessfullyUpdated;
                               
                                ddlFileUploadType.SelectedIndex = 0;
                                ScriptManager.RegisterStartupScript(ddlOption, ddlOption.GetType(), Guid.NewGuid().ToString(), "ShowHideDiv('divUpload',true);", true);
                                LoadUploadDocument();
                            }
                            else
                            {
                                Span1.InnerHtml = Resources.General.UploadFileNameSaveFailed;
                                ScriptManager.RegisterStartupScript(ddlOption, ddlOption.GetType(), Guid.NewGuid().ToString(), "ShowHideDiv('divUpload',true);", true);
                            }
                        }
                        catch (Exception ex)
                        {
                            Span1.InnerHtml = Resources.General.FileUploadFailed;
                            ScriptManager.RegisterStartupScript(ddlOption, ddlOption.GetType(), Guid.NewGuid().ToString(), "ShowHideDiv('divUpload',true);", true);
                        }
                    }
                    else
                    {
                        Span1.InnerHtml = Resources.General.Maximum1MB;
                        ScriptManager.RegisterStartupScript(ddlOption, ddlOption.GetType(), Guid.NewGuid().ToString(), "ShowHideDiv('divUpload',true);", true);
                    }
                }
                else
                {
                    Span1.InnerHtml = Resources.General.PDFformat;
                    ScriptManager.RegisterStartupScript(ddlOption, ddlOption.GetType(), Guid.NewGuid().ToString(), "ShowHideDiv('divUpload',true);", true);
                }
            }
            else
            {
                Span1.InnerHtml = Resources.General.ChooseDocument;
                ScriptManager.RegisterStartupScript(ddlOption, ddlOption.GetType(), Guid.NewGuid().ToString(), "ShowHideDiv('divUpload',true);", true);
            }
        }
        else
        {
            Span1.InnerHtml = Resources.General.ChooseDocument;
            ScriptManager.RegisterStartupScript(ddlOption, ddlOption.GetType(), Guid.NewGuid().ToString(), "ShowHideDiv('divUpload',true);", true);
        }
    }

    protected void btnPaymentApproval_Click(object sender, EventArgs e)
    {
        try
        {
            if (Session[General.UserRole].ToString() == "100")
            {
                lblCashierApproveMessage.Text = Resources.Proposal.AccessDenied;
                lblCashierApproveMessage.ForeColor = System.Drawing.Color.Red;
                return;
            }
            Int32 _AppCount = 0;
            MyDatabase _myappDB = new MyDatabase();
            string strSelectSql = "SELECT COUNT(*) RecordCount FROM tblNonGGCarMoreDetails WHERE CECarId = " + txtCarId.Text + " AND QuoteRefNo = '" + lblUpRefNo.Text.Trim() + "' AND [Status] = 1";
            DataTable _SelectItemResult = _myappDB.GetDataTable(strSelectSql);
            if (_SelectItemResult != null && _SelectItemResult.Rows.Count > 0)
            {
                if (_SelectItemResult.Rows[0]["RecordCount"] != DBNull.Value)
                {
                    _AppCount = Convert.ToInt32(_SelectItemResult.Rows[0]["RecordCount"].ToString());
                }
            }
            if (_AppCount <= 0)
            {
                lblCashierApproveMessage.Text = "Application not found!";
                lblCashierApproveMessage.ForeColor = System.Drawing.Color.Red;
                return;
            }
            lblPayError.Text = "";
            lblOnlinePayError.Text = "";
            lblCashierApproveMessage.Text = "";
            Page.Validate("specialpay");
            lblLoadMessage.Text = string.Empty;
            if (Page.IsValid)
            {
                if (Session[CE.Global.General.UserRole] != null && Session[CE.Global.General.UserRole].ToString() == "300")
                {       
                    Int64 _result = -1;
                    Int64 CECarId = 0;
                    Int64 ProviderCompanyId = 0;
                    Int16 TescoSelect = 0;
                    decimal TescoAmount = 0;
                    decimal ApprovedPremium = 0;
                    Int64 ApprovedAgentId = 0;
                    if(!Int64.TryParse(txtCarId.Text.Trim(), out CECarId))
                    {
                        CECarId = 0;
                    }
                    if(!Int64.TryParse(txtProviderId.Text.Trim(), out ProviderCompanyId))
                    {
                        ProviderCompanyId = 0;
                    }
                    if(!Int16.TryParse(txtTescoSelectedId.Text.Trim(), out TescoSelect))
                    {
                        TescoSelect = 0;
                    }
                    if(!decimal.TryParse(txtTescoAmount.Text.Trim(), out TescoAmount))
                    {
                        TescoAmount = 0;
                    }
                    if(!decimal.TryParse(txtFinalApprovalPremium.Text.Trim(), out ApprovedPremium))
                    {
                        ApprovedPremium = 0;
                    }
                    if (!Int64.TryParse(Session[General.UserId].ToString(), out ApprovedAgentId))
                    {
                        ApprovedAgentId = 0;
                    }

                    DateTime _dtApprovalDateTime = dateTimeNow;
                    if (txtApprovalDate.Text.Trim() != "")
                    {
                        _dtApprovalDateTime = Convert.ToDateTime(txtApprovalDate.Text);
                        _dtApprovalDateTime = new DateTime(_dtApprovalDateTime.Year, _dtApprovalDateTime.Month, _dtApprovalDateTime.Day, dateTimeNow.Hour, dateTimeNow.Minute, dateTimeNow.Second, dateTimeNow.Millisecond);
                    }

                    string _spName = "sprocCXCRMCashierApprovalUpdateSingleItem";
                    SortedList _sPara = new SortedList();
                    #region Parameter
                    _sPara.Add("@CECarId", CECarId);
                    _sPara.Add("@ProviderCompanyId", ProviderCompanyId);
                    _sPara.Add("@TescoSelect", TescoSelect);
                    _sPara.Add("@TescoAmount", TescoAmount);
                    _sPara.Add("@ApprovedPremium", ApprovedPremium);
                    _sPara.Add("@Approved", 1);
                    _sPara.Add("@ApprovedAgentId", ApprovedAgentId);
                    _sPara.Add("@QuoteRefNo", lblUpRefNo.Text.Trim());
                    _sPara.Add("@Info9", Server.HtmlEncode(txtApprovalRemark.Text)); // Remarks
                    _sPara.Add("@ApprovedDate", _dtApprovalDateTime);
                    #endregion

                    _result = _myappDB.ExecuteSP(_spName, _sPara);

                    if (_result > 0)
                    {
                        if (txtPaymentStatus.Text.Trim() == "0")
                        {
                            string _spTName = "sprocCXCRMNonGGTransactionInsertUpdateSingleItem";
                            SortedList _sTPara = new SortedList();

                            _sTPara.Add("@TransactionID", txtTransactionId.Text);
                            if (Session[General.UserRole].ToString() == "100")
                            {
                                _sTPara.Add("@AgentID", Session[General.UserId].ToString());
                                _sTPara.Add("@AdminID", 0);
                            }
                            else
                            {
                                _sTPara.Add("@AdminID", Session[General.UserId].ToString());
                                _sTPara.Add("@AgentID", 0);
                            }
                            _sTPara.Add("@CECarId", txtCarId.Text);
                            _sTPara.Add("@RefCEUserId", txtUserId.Text);
                            _sTPara.Add("@ProviderCompanyId", txtProviderId.Text);
                            _sTPara.Add("@QuoteRefNo", lblUpRefNo.Text.Trim());
                            _sTPara.Add("@TransactionTypeId", 100);
                            _sTPara.Add("@Remarks", Server.HtmlEncode(txtApprovalRemark.Text));
                            _sTPara.Add("@Info1", null);
                            _sTPara.Add("@Info2", null);
                            _sTPara.Add("@FInfo1", null);
                            _sTPara.Add("@Status", true);
                            Int64 _transID = Convert.ToInt64(_myappDB.ExecuteNonSqlSP(_spTName, _sTPara));
                            
                            if (_transID > 0)
                            {
                                LoadPaymentCompletedStatus();
                            }
                            else
                            {
                                lblPaymentStatusMessage.Text = "Payment Completed Status Updated Error!";
                            }
                        }

                        if (txtTransactionId.Text != "-1")
                        {
                            //Update CreatedDate For
                            SortedList _sGGTPara = new SortedList();
                            _sGGTPara.Add("@ApprovedDate", _dtApprovalDateTime);
                            _myappDB.ExecuteNonSqlStatement("UPDATE tblNonGGTransaction SET CreatedDate = @ApprovedDate, ModifiedDate = @ApprovedDate WHERE TransactionId = " + txtTransactionId.Text.Trim(), _sGGTPara);
                        }

                        txtFinalPrice.Text = txtFinalApprovalPremium.Text;
                        PaymentGridLoad();
                        ShowTescoAmount();
                        lblCashierApproveMessage.Text = "Premium Updated and Payment Approved!";
                        lblCashierApproveMessage.ForeColor = System.Drawing.Color.Green;

                        string AgentEmail = "";
                        string strSql = "";
                        MyDatabase _db = new MyDatabase();
                        // No DECRYPTION
//                        strSql = @"SELECT CU.UserLogin AS Email FROM tblCEUser CU INNER JOIN 
//                                   tblCXBrokerPremium BP ON BP.AgentId = CU.CEID WHERE BP.SelectedStatus = 1 ";
//                        strSql += "AND BP.CECarId = " + txtCarId.Text + " AND BP.Info1 = '" + lblUpRefNo.Text.Trim() + "' ";
                        strSql = @"OPEN SYMMETRIC KEY CXUserSym
                                DECRYPTION BY CERTIFICATE CXUserCert
                                SELECT CONVERT(VARCHAR(50), DECRYPTBYKEY(CU.EInfo1)) Email FROM tblCEUser CU INNER JOIN 
                                tblCXBrokerPremium BP ON BP.AgentId = CU.CEID WHERE BP.SelectedStatus = 1 ";
                        strSql += "AND BP.CECarId = " + txtCarId.Text + " AND BP.Info1 = '" + lblUpRefNo.Text.Trim() + "' ";
                        strSql += "CLOSE SYMMETRIC KEY CXUserSym";

                        object _agentEmail = _db.ExecuteScalarSqlStatement(strSql);
                        if (_agentEmail != null)
                        {
                            AgentEmail = _agentEmail.ToString();
                            SendApproveMailStatusToBroker(txtCustomerName.Text, AgentEmail);
                        }
                    }
                    else
                    {
                        lblCashierApproveMessage.Text = "Premium Updated Error!";
                        lblCashierApproveMessage.ForeColor = System.Drawing.Color.Red;
                    }
                   
                }
                else
                {
                    lblCashierApproveMessage.Text = Resources.Proposal.AccessDenied;
                    lblCashierApproveMessage.ForeColor = System.Drawing.Color.Red;
                }
            }
        }
        catch (Exception ex)
        {
        }
    }

    public bool SendApproveMailStatusToBroker(string CustomerName, string BrokerEmail)
    {
        bool _result = true;
        string mailBody = "";
        string _emailTitle = "";
        string _toemail = "";
        string _ccemail = "";
        string _bccemail = "";
        _emailTitle = "[" + lblUpRefNo.Text + "] [Approved] ";
        mailBody = Resources.General.CustomerName + " : " + CustomerName + "<br/><br/>";
        mailBody += "Final Approval Premium : " + txtFinalApprovalPremium.Text + "<br/><br/>";
        if (chkTescoCash.Checked)
        {
            mailBody += "Tesco : " + txtTescoAmount.Text + "<br/><br/>";
        }
        else
        {
            mailBody += "Tesco : <br/><br/>";
        }
        mailBody += Resources.General.Status + " : <b style='color:green;'>" + Resources.CarInsurance.Approve + "</b><br/><br/>";
        mailBody += Resources.General.DateTime + " : " + dateTimeNow.ToString("dd-MMM-yyyy hh:mm:ss tt") + "<br/><br/>";
        _toemail = CE.Configuration.MyConfigurationManager.GetAppSettingValue("ADMIN");
        if (!BrokerEmail.Trim().Contains("_renewal"))
        {
            _toemail += BrokerEmail;
        }
        else
        {
            //_toemail += "broker8@comparexpress.co.th";
            string _nEmail = BrokerEmail.Trim().Replace("_renewal", "");
            _toemail += _nEmail;
        }
        _bccemail = "";

        /* Hide on 08/Jan/2014
        if (Session[General.UserRole].ToString() == "100")
        {
            _ccemail += Session[General.SMTPReplyTo].ToString();
        }*/

        _result = MyMailManager.SendGGMail(ConfigurationManager.AppSettings["GGFormsSMTPAccount"].ToString(), ConfigurationManager.AppSettings["GGFormsSMTPAuthCode"].ToString(), _toemail, _ccemail, _bccemail, _emailTitle, mailBody, Session[General.SMTPReplyTo].ToString());

        return _result;
    }

    //OnSelectedIndexChanged="grvPayment_SelectedIndexChanged"
    protected void grvPayment_SelectedIndexChanged(object sender, EventArgs e)
    {
        lblPayError.Text = "";
        txtApproveStatus.Text = "0";
        if (grvPayment.Rows.Count > 0)
        {
            if (grvPayment.SelectedIndex >= 0)
            {
                

                btnPayDecline.Visible = true;
                btnPaySubmit.Text = Resources.CarInsurance.Approve;
                GridViewRow row = grvPayment.SelectedRow;
                txtPaymentId.Text = grvPayment.SelectedDataKey[0].ToString();
                txtStatus.Text = grvPayment.SelectedDataKey[12].ToString();
                if (grvPayment.SelectedDataKey[13] != null && grvPayment.SelectedDataKey[13].ToString() != string.Empty)
                {
                    ddlBank.Text = grvPayment.SelectedDataKey[13].ToString();
                }
                if (grvPayment.SelectedDataKey[15] != null && grvPayment.SelectedDataKey[15].ToString() != string.Empty)
                {
                    txtAgentRemarks.Text = grvPayment.SelectedDataKey[15].ToString();
                }
                //divCC.Visible = false;
                //rfvCVV.Enabled = false;
                //revCVV.Enabled = false;
                EnableDisable();
                if (grvPayment.SelectedDataKey[3].ToString() == "1")
                {
                    chkRefund.Checked = false;
                    ddlPaymentOption.Text = grvPayment.SelectedDataKey[1].ToString();
                    ddlPaymentOption_SelectedIndexChanged(null, null);
                    ddlPaymentType.Text = grvPayment.SelectedDataKey[2].ToString();
                    ddlPaymentType_SelectedIndexChanged(null, null);
                }
                else
                {
                    chkRefund.Checked = true;
                }
                txtAmount.Text = row.Cells[2].Text;
                txtAmount.ReadOnly = true;
                if (grvPayment.SelectedDataKey[14] != null && grvPayment.SelectedDataKey[14].ToString() != string.Empty && ddlPaymentOption.Text == "IP")
                {
                    if (!chkRefund.Checked)
                    {
                        ddlNoOfInstallments.Text = grvPayment.SelectedDataKey[14].ToString();
                        ddlNoOfInstallments_SelectedIndexChanged(null, null);
                    }
                }
                else
                {
                    ddlNoOfInstallments.Text = "-1";
                    ddlNoOfInstallments_SelectedIndexChanged(null, null);
                }
                if (grvPayment.SelectedDataKey[4].ToString() == "1")
                {
                    //chkApprove.Checked = true;
                    btnPaySubmit.Enabled = false;
                    btnPayDecline.Visible = false;
                }
                else
                {
                    //chkApprove.Checked = false;
                    btnPaySubmit.Enabled = true;
                }
                if (grvPayment.SelectedDataKey[6] != null && grvPayment.SelectedDataKey[6].ToString() != string.Empty)
                {
                    if (grvPayment.SelectedDataKey[6].ToString().ToLower() == "kasikorn bank")
                    {
                        ddlIssuingBank.Items.Clear();
                        ddlIssuingBank.Items.Add(new ListItem(GetBankName("KBANK"), "KBANK"));
                        txtIssuingBank.Text = "Kasikorn Bank";
                    }
                    else if (grvPayment.SelectedDataKey[6].ToString().ToLower() == "bangkok bank")
                    {
                        ddlIssuingBank.Items.Clear();
                        ddlIssuingBank.Items.Add(new ListItem(GetBankName("BKK"), "BKK"));
                        txtIssuingBank.Text = "Bangkok Bank";
                    }
                    else if (grvPayment.SelectedDataKey[6].ToString().ToLower() == "citibank")
                    {
                        ddlIssuingBank.Items.Clear();
                        ddlIssuingBank.Items.Add(new ListItem(GetBankName("CITI"), "CITI"));
                        txtIssuingBank.Text = "Citibank";
                    }
                    else if (grvPayment.SelectedDataKey[6].ToString().ToLower() == "ktc")
                    {
                        ddlIssuingBank.Items.Clear();
                        ddlIssuingBank.Items.Add(new ListItem(GetBankName("KTC"), "KTC"));
                        txtIssuingBank.Text = "KTC";
                    }
                    else if (grvPayment.SelectedDataKey[6].ToString().ToLower() == "bank of ayudhaya")
                    {
                        ddlIssuingBank.Items.Clear();
                        ddlIssuingBank.Items.Add(new ListItem(GetBankName("AYA"), "AYA"));
                        txtIssuingBank.Text = "Bank of Ayudhaya";
                    }
                    else if (grvPayment.SelectedDataKey[6].ToString().ToLower() == "central card")
                    {
                        ddlIssuingBank.Items.Clear();
                        ddlIssuingBank.Items.Add(new ListItem(GetBankName("CTRL"), "CTRL"));
                        txtIssuingBank.Text = "Central Card";
                    }
                    else if (grvPayment.SelectedDataKey[6].ToString().ToLower() == "robinson card")
                    {
                        ddlIssuingBank.Items.Clear();
                        ddlIssuingBank.Items.Add(new ListItem(GetBankName("RBSN"), "RBSN"));
                        txtIssuingBank.Text = "Robinson Card";
                    }
                    else if (grvPayment.SelectedDataKey[6].ToString().ToLower() == "homepro card")
                    {
                        ddlIssuingBank.Items.Clear();
                        ddlIssuingBank.Items.Add(new ListItem(GetBankName("HPRO"), "HPRO"));
                        txtIssuingBank.Text = "Homepro Card";
                    }
                }
                txtApproveStatus.Text = grvPayment.SelectedDataKey[4].ToString();
                chkApprove.Checked = true;
                chkApprove.Enabled = false;
                
                if (chkRefund.Checked == false)
                {
                    if (ddlPaymentType.Text == "CCIP" || ddlPaymentType.Text == "CCOL")
                    {
                        pnlCreditCard.Visible = true;
                        txtIssuingBank.Text = grvPayment.SelectedDataKey[6].ToString();
                        if (txtOnlineApproveStatus.Text != string.Empty && txtOnlineApproveStatus.Text != "1")
                        {
                            ddlCardType.Text = grvPayment.SelectedDataKey[9].ToString();
                           
                            //txtCardExpiryMonth.Text = grvPayment.SelectedDataKey[7].ToString();
                            //txtCardExpiryYear.Text = grvPayment.SelectedDataKey[8].ToString();
                        }
                        //txtCardHolder.Text = grvPayment.SelectedDataKey[5].ToString();
                        //txtCVV.Text = grvPayment.SelectedDataKey[10].ToString();
                        //string CC = row.Cells[2].Text;
                        //for (int i = 0; i < 4; i++)
                        //{
                        //    if (i == 0)
                        //    {
                        //        txtCardNo1.Text = CC.Substring(0, 4);
                        //    }
                        //    if (i == 1)
                        //    {
                        //        txtCardNo2.Text = CC.Substring(4, 4);
                        //    }
                        //    if (i == 2)
                        //    {
                        //        txtCardNo3.Text = CC.Substring(8, 4);
                        //    }
                        //    if (i == 3)
                        //    {
                        //        txtCardNo4.Text = CC.Substring(12, 4);
                        //    }
                        //}
                    }
                    else
                    {
                        pnlCreditCard.Visible = false;
                        txtIssuingBank.Text = "";
                        ddlCardType.SelectedIndex = 0;

                        //txtCardNo1.Text = "";
                        //txtCardNo2.Text = "";
                        //txtCardNo3.Text = "";
                        //txtCardNo4.Text = "";
                        //txtCardHolder.Text = "";
                        //txtCVV.Text = "000";
                        //txtCardExpiryMonth.Text = "";
                        //txtCardExpiryYear.Text = "";
                    }
                }
                else
                {
                    //txtCardNo1.Text = "";
                    //txtCardNo2.Text = "";
                    //txtCardNo3.Text = "";
                    //txtCardNo4.Text = "";
                    //txtCardHolder.Text = "";
                    //txtCVV.Text = "000";
                    //txtCardExpiryMonth.Text = "";
                    //txtCardExpiryYear.Text = "";

                    pnlCreditCard.Visible = false;
                    txtIssuingBank.Text = "";
                    ddlCardType.SelectedIndex = 0;
                    
                    ddlPaymentType.SelectedIndex = 0;
                    ddlPaymentOption.SelectedIndex = 0;
                }
                EnablePaymentOnOff();
                txtPaymentRefNo.Text = grvPayment.SelectedDataKey[11].ToString();

                if (txtPaymentId.Text == "0")
                {
                    chkRefund.Enabled = true;
                }
                else
                {
                    chkRefund.Enabled = false;
                }
            }
            else
            {
                txtPaymentId.Text = "0";
                btnPaySubmit.Text = Resources.General.Submit;
                EnableDisable();
            }
        }
        else
        {
            txtPaymentId.Text = "0";
            btnPaySubmit.Text = Resources.General.Submit;
            EnableDisable();
        }
    }

    protected void grvPayment_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string _Approve = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "ApproveType"));
            string _Refund = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Transaction"));
           
            if (_Approve == "1")
            {
                e.Row.Cells[6].ForeColor = System.Drawing.Color.Green;
            }
            else
            {
                e.Row.Cells[6].ForeColor = System.Drawing.Color.Red;
            }

            if (_Refund.ToUpper() == "REFUND")
            {
                e.Row.Cells[1].ForeColor = System.Drawing.Color.Red;
            }
            else
            {
                e.Row.Cells[1].ForeColor = System.Drawing.Color.Green;
            }

            Button btnDelete = (Button)e.Row.FindControl("btnDelete");
            btnDelete.Enabled = false;
            if (Session[General.UserRole] != null && Session[General.UserRole].ToString() == "300")
            {
                btnDelete.Enabled = CheckPaymentCompletedStatusDate();
            }

            Button btnEdit = (Button)e.Row.FindControl("btnEdit");
            btnEdit.Enabled = false;
            if (Session[General.UserRole] != null && Session[General.UserRole].ToString() != "100")
            {
                if (_Approve != "1")
                {
                    btnEdit.Enabled = true;
                }
            }
        }
        
    }

    protected void grvPayment_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        Span1.InnerHtml = "";
        if (e.CommandName.Equals("MyDelete"))
        {
            if (e.CommandArgument != null)
            {
                Int64 PaymentId = 0;
                Int64 CECarId = 0;
                Int64 AdminId = 0;

                Int64 _result = -1;
                CECarId = Convert.ToInt64(txtCarId.Text);
                AdminId = Convert.ToInt64(Session[General.UserId].ToString());
                PaymentId = Convert.ToInt64(e.CommandArgument);

                NonGGPackageDB _nonggpackagedb = new NonGGPackageDB();
                _result = _nonggpackagedb.DeclineNonGGPayment(CECarId, AdminId, PaymentId);

                if (_result > 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Delete was successful.');", true);
                }
                else
                {
                    ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Delete failed.');", true);
                }
                PaymentGridLoad();
            }
        }
        else if (e.CommandName.Equals("MyEdit"))
        {
            if (e.CommandArgument != null)
            {
                //Int64 PaymentId = 0;
                //PaymentId = Convert.ToInt64(e.CommandArgument);
                
                GridViewRow gvr = (GridViewRow)((Control)e.CommandSource).NamingContainer;
                int rowIndex = gvr.RowIndex;
                grvPayment.SelectedIndex = rowIndex;

                lblPayError.Text = "";
                txtApproveStatus.Text = "0";

                GridViewRow row = grvPayment.SelectedRow;
                txtPaymentId.Text = "0";
                // Allow to edit
                EnableDisable();
                txtPaymentId.Text = grvPayment.SelectedDataKey[0].ToString();
                txtStatus.Text = grvPayment.SelectedDataKey[12].ToString();
                if (grvPayment.SelectedDataKey[13] != null && grvPayment.SelectedDataKey[13].ToString() != string.Empty)
                {
                    ddlBank.Text = grvPayment.SelectedDataKey[13].ToString();
                }
                if (grvPayment.SelectedDataKey[15] != null && grvPayment.SelectedDataKey[15].ToString() != string.Empty)
                {
                    txtAgentRemarks.Text = grvPayment.SelectedDataKey[15].ToString();
                }

                if (grvPayment.SelectedDataKey[3].ToString() == "1")
                {
                    chkRefund.Checked = false;
                    ddlPaymentOption.Text = grvPayment.SelectedDataKey[1].ToString();
                    ddlPaymentOption_SelectedIndexChanged(null, null);
                    ddlPaymentType.Text = grvPayment.SelectedDataKey[2].ToString();
                    ddlPaymentType_SelectedIndexChanged(null, null);
                }
                else
                {
                    chkRefund.Checked = true;
                }
                txtAmount.Text = row.Cells[2].Text;
                //txtAmount.ReadOnly = true;
                if (grvPayment.SelectedDataKey[14] != null && grvPayment.SelectedDataKey[14].ToString() != string.Empty && ddlPaymentOption.Text == "IP")
                {
                    if (!chkRefund.Checked)
                    {
                        ddlNoOfInstallments.Text = grvPayment.SelectedDataKey[14].ToString();
                        ddlNoOfInstallments_SelectedIndexChanged(null, null);
                    }
                }
                else
                {
                    ddlNoOfInstallments.Text = "-1";
                    ddlNoOfInstallments_SelectedIndexChanged(null, null);
                }
                if (grvPayment.SelectedDataKey[4].ToString() == "1")
                {
                    //chkApprove.Checked = true;
                    btnPaySubmit.Enabled = false;
                    btnPayDecline.Visible = false;
                }
                else
                {
                    //chkApprove.Checked = false;
                    btnPaySubmit.Enabled = true;
                }
                if (grvPayment.SelectedDataKey[6] != null && grvPayment.SelectedDataKey[6].ToString() != string.Empty)
                {
                    if (grvPayment.SelectedDataKey[6].ToString().ToLower() == "kasikorn bank")
                    {
                        ddlIssuingBank.Items.Clear();
                        ddlIssuingBank.Items.Add(new ListItem(GetBankName("KBANK"), "KBANK"));
                        txtIssuingBank.Text = "Kasikorn Bank";
                    }
                    else if (grvPayment.SelectedDataKey[6].ToString().ToLower() == "bangkok bank")
                    {
                        ddlIssuingBank.Items.Clear();
                        ddlIssuingBank.Items.Add(new ListItem(GetBankName("BKK"), "BKK"));
                        txtIssuingBank.Text = "Bangkok Bank";
                    }
                    else if (grvPayment.SelectedDataKey[6].ToString().ToLower() == "citibank")
                    {
                        ddlIssuingBank.Items.Clear();
                        ddlIssuingBank.Items.Add(new ListItem(GetBankName("CITI"), "CITI"));
                        txtIssuingBank.Text = "Citibank";
                    }
                    else if (grvPayment.SelectedDataKey[6].ToString().ToLower() == "ktc")
                    {
                        ddlIssuingBank.Items.Clear();
                        ddlIssuingBank.Items.Add(new ListItem(GetBankName("KTC"), "KTC"));
                        txtIssuingBank.Text = "KTC";
                    }
                    else if (grvPayment.SelectedDataKey[6].ToString().ToLower() == "bank of ayudhaya")
                    {
                        ddlIssuingBank.Items.Clear();
                        ddlIssuingBank.Items.Add(new ListItem(GetBankName("AYA"), "AYA"));
                        txtIssuingBank.Text = "Bank of Ayudhaya";
                    }
                    else if (grvPayment.SelectedDataKey[6].ToString().ToLower() == "central card")
                    {
                        ddlIssuingBank.Items.Clear();
                        ddlIssuingBank.Items.Add(new ListItem(GetBankName("CTRL"), "CTRL"));
                        txtIssuingBank.Text = "Central Card";
                    }
                    else if (grvPayment.SelectedDataKey[6].ToString().ToLower() == "robinson card")
                    {
                        ddlIssuingBank.Items.Clear();
                        ddlIssuingBank.Items.Add(new ListItem(GetBankName("RBSN"), "RBSN"));
                        txtIssuingBank.Text = "Robinson Card";
                    }
                    else if (grvPayment.SelectedDataKey[6].ToString().ToLower() == "homepro card")
                    {
                        ddlIssuingBank.Items.Clear();
                        ddlIssuingBank.Items.Add(new ListItem(GetBankName("HPRO"), "HPRO"));
                        txtIssuingBank.Text = "Homepro Card";
                    }
                }
                txtApproveStatus.Text = grvPayment.SelectedDataKey[4].ToString();
                //chkApprove.Checked = true;
                chkApprove.Enabled = false;

                if (chkRefund.Checked == false)
                {
                    if (ddlPaymentType.Text == "CCIP" || ddlPaymentType.Text == "CCOL")
                    {
                        pnlCreditCard.Visible = true;
                        txtIssuingBank.Text = grvPayment.SelectedDataKey[6].ToString();
                        if (txtOnlineApproveStatus.Text != string.Empty && txtOnlineApproveStatus.Text != "1")
                        {
                            ddlCardType.Text = grvPayment.SelectedDataKey[9].ToString();
                        }
                    }
                    else
                    {
                        pnlCreditCard.Visible = false;
                        txtIssuingBank.Text = "";
                        ddlCardType.SelectedIndex = 0;
                    }
                }
                else
                {
                    pnlCreditCard.Visible = false;
                    txtIssuingBank.Text = "";
                    ddlCardType.SelectedIndex = 0;

                    ddlPaymentType.SelectedIndex = 0;
                    ddlPaymentOption.SelectedIndex = 0;
                }
                EnablePaymentOnOff();
                txtPaymentRefNo.Text = grvPayment.SelectedDataKey[11].ToString();

                if (txtPaymentId.Text == "0")
                {
                    chkRefund.Enabled = true;
                }
                else
                {
                    chkRefund.Enabled = false;
                }
            }
        }
    }

    protected void grvFileUpload_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        Span1.InnerHtml = "";
        if (e.CommandName.Equals("MyDelete"))
        {
            if (e.CommandArgument != null)
            {
                GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
                Label lblFLCarId = (Label)row.FindControl("lblFLCarId");

                Int64 _FileId = 0;
                Int64 _CECarId = 0;
                Int64 _AgentId = 0;
                _FileId = Convert.ToInt64(e.CommandArgument);
                _CECarId = Convert.ToInt64(lblFLCarId.Text);
                _AgentId = Convert.ToInt64(Session[CE.Global.General.UserId].ToString());
               
                MyDatabase _db = new MyDatabase();
                SortedList _paraList = new SortedList();
                _paraList.Add("@FileId", _FileId);
                _paraList.Add("@CECarId", _CECarId);
                _paraList.Add("@AgentId", _AgentId);
                int _effCount = _db.ExecuteNonSqlSP("sprocCXCRMNonGGUploadCarFileDeleteSingleItem", _paraList);
                if (_effCount > 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Delete was successful.');", true);
                }
                else
                {
                    ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Delete failed.');", true);
                }
                
                Label lblPath = (Label)row.FindControl("lblPath");
                MyIO _myIO = new MyIO();
                _myIO.DeleteFile(lblPath.Text);
                LoadUploadDocument();
            }
        }
    }

    protected void grvFileUpload_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            HyperLink hplk = (HyperLink)e.Row.FindControl("hplDownLoad");
            Label Path = (Label)e.Row.FindControl("lblPath");

            if (hplk != null)
            {
                hplk.NavigateUrl = "DownLoad/UploadNonGGHandler.ashx?FileName=" + Path.Text;
            }

            Label FileName = (Label)e.Row.FindControl("lblPDFFileName");
            Label FileType = (Label)e.Row.FindControl("lblPDFFileType");
            string strFileName = FileName.Text;
            System.IO.FileInfo _File = new System.IO.FileInfo(strFileName.ToString());
            FileName.Text = FileType.Text.Replace(' ', '_') + "_" + lblUpRefNo.Text + "_" + (e.Row.RowIndex + 1).ToString() + _File.Extension;

            
        }
    }

    private bool SaveDriverDetails()
    {
        bool _result = false;
        NonGGCarDriver _nonggcardriver = new NonGGCarDriver();
        NonGGCarDriverDB _nonggcardriverdb = new NonGGCarDriverDB();

        if (ddlNamedDriver.Text != "0")
        {
            int _drivercount = Convert.ToInt32(ddlNamedDriver.Text);
            int _insertcount = 0;

            for (int i = 1; i <= _drivercount; i++)
            {
                if (Session[CE.Global.General.UserId] != null)
                {
                    _nonggcardriver.AgentId = Convert.ToInt64(Session[CE.Global.General.UserId].ToString());
                }
                else
                {
                    _nonggcardriver.AgentId = 0;
                }
                _nonggcardriver.RefCEUserId = Convert.ToInt64(txtUserId.Text);
                _nonggcardriver.CECarId = Convert.ToInt64(txtCarId.Text);
                if (i == 1)
                {
                    _nonggcardriver.CarDriverId = Convert.ToUInt32(txtDriverId1.Text);
                    _nonggcardriver.FullName = Server.HtmlEncode(txtDriverFirst.Text.Trim());
                    DateTime _dtDriver1DOB = new DateTime(Convert.ToInt32(ddlDriver1DOBYear.Text), Convert.ToInt32(ddlDriver1DOBMonth.Text), Convert.ToInt32(ddlDriver1DOBDay.Text));
                    _nonggcardriver.DOB = _dtDriver1DOB;
                    _nonggcardriver.IDNo = Server.HtmlEncode(txtDriver1IDNo.Text.Trim());
                    _nonggcardriver.DrivingLicenseNumber = Server.HtmlEncode(txtDriver1LicenseNo.Text.Trim());
                    _nonggcardriver.Status = true;
                }
                else if (i == 2)
                {
                    _nonggcardriver.CarDriverId = Convert.ToUInt32(txtDriverId2.Text); ;
                    _nonggcardriver.FullName = Server.HtmlEncode(txtDriverTwo.Text.Trim());
                    DateTime _dtDriver2DOB = new DateTime(Convert.ToInt32(ddlDriver2DOBYear.Text), Convert.ToInt32(ddlDriver2DOBMonth.Text), Convert.ToInt32(ddlDriver2DOBDay.Text));
                    _nonggcardriver.DOB = _dtDriver2DOB;
                    _nonggcardriver.IDNo = Server.HtmlEncode(txtDriver2IDNo.Text.Trim());
                    _nonggcardriver.DrivingLicenseNumber = Server.HtmlEncode(txtDriver2LicenseNo.Text.Trim());
                    _nonggcardriver.Status = true;
                }
                if (_nonggcardriverdb.Insert(_nonggcardriver) > 0)
                {
                    _insertcount++;
                    _result = true;
                }
            }
            _nonggcardriverdb = null;
            _nonggcardriver = null;
        }
        return _result;
    }

    private string GetExcelFilePath(Int64 ProviderCompanyId, string QuoteRefNo)
    {
        string _filePath = CE.Configuration.MyConfigurationManager.GetAppSettingValue("NonGGFileOutputPath").ToString();
        string _provider = CE.Global.General.GetProvider(ProviderCompanyId);
        CE.InputOut.MyIO _myIO = new CE.InputOut.MyIO();
        string _currentMonth = dateTimeNow.ToString("yyyyMMM");
        string _todaydate = dateTimeNow.ToString("yyyyMMMdd");
        _filePath += "exceloutput\\" + _provider + "\\";
        if (!_myIO.CheckDirectory(_filePath + _currentMonth))
        {
            if (_myIO.CreateDirectory(_filePath, _currentMonth))
            {
                _filePath += _currentMonth + "\\";
            }
        }
        else
        {
            _filePath += _currentMonth + "\\";
        }

        if (!_myIO.CheckDirectory(_filePath + _todaydate))
        {
            if (_myIO.CreateDirectory(_filePath, _todaydate))
            {
                _filePath += _todaydate + "\\";
            }
        }
        else
        {
            _filePath += _todaydate + "\\";
        }

        if (!_myIO.CheckDirectory(_filePath + QuoteRefNo))
        {
            if (_myIO.CreateDirectory(_filePath, QuoteRefNo))
            {
                _filePath += QuoteRefNo + "\\";
            }
        }
        else
        {
            _filePath += QuoteRefNo + "\\";
        }
        return _filePath;
    }

    private string GetPdfFilePath(Int64 ProviderCompanyId, string QuoteRefNo)
    {
        //Currently Not Use=ing
        string _filePath = CE.Configuration.MyConfigurationManager.GetAppSettingValue("NonGGFileOutputPath").ToString();
        string _provider = CE.Global.General.GetProvider(ProviderCompanyId);
        string _currentMonth = dateTimeNow.ToString("yyyyMMM");
        string _todaydate = dateTimeNow.ToString("yyyyMMMdd");
        _filePath += "upload\\" + _provider + "\\";
        CE.InputOut.MyIO _myIO = new CE.InputOut.MyIO();
        if (!_myIO.CheckDirectory(_filePath + _currentMonth))
        {
            if (_myIO.CreateDirectory(_filePath, _currentMonth))
            {
                _filePath += _currentMonth + "\\";
            }
        }
        else
        {
            _filePath += _currentMonth + "\\";
        }

        if (!_myIO.CheckDirectory(_filePath + _todaydate))
        {
            if (_myIO.CreateDirectory(_filePath, _todaydate))
            {
                _filePath += _todaydate + "\\";
            }
        }
        else
        {
            _filePath += _todaydate + "\\";
        }

        if (!_myIO.CheckDirectory(_filePath + QuoteRefNo))
        {
            if (_myIO.CreateDirectory(_filePath, QuoteRefNo))
            {
                _filePath += QuoteRefNo + "\\";
            }
        }
        else
        {
            _filePath += QuoteRefNo + "\\";
        }
        return _filePath;
    }

    private string GetPdfFilePath(string FileType)
    {
        string _filePath = CE.Configuration.MyConfigurationManager.GetAppSettingValue("NonGGFileOutputPath").ToString();
        _filePath += "upload\\carinsurance\\";
        CE.InputOut.MyIO _myIO = new CE.InputOut.MyIO();

        string _curYear = dateTimeNow.ToString("yyyy");
        if (!_myIO.CheckDirectory(_filePath + _curYear))
        {
            if (_myIO.CreateDirectory(_filePath, _curYear))
            {
                _filePath += _curYear + "\\";
            }
        }
        else
        {
            _filePath += _curYear + "\\";
        }

        string _curMonth = dateTimeNow.ToString("MMMM");
        if (!_myIO.CheckDirectory(_filePath + _curMonth))
        {
            if (_myIO.CreateDirectory(_filePath, _curMonth))
            {
                _filePath += _curMonth + "\\";
            }
        }
        else
        {
            _filePath += _curMonth + "\\";
        }

        string _todaydate = dateTimeNow.ToString("ddMMMMyyyy");
        if (!_myIO.CheckDirectory(_filePath + _todaydate))
        {
            if (_myIO.CreateDirectory(_filePath, _todaydate))
            {
                _filePath += _todaydate + "\\";
            }
        }
        else
        {
            _filePath += _todaydate + "\\";
        }

        string _quotes = FileType.ToString() + "_" + _todaydate;
        if (!_myIO.CheckDirectory(_filePath + _quotes))
        {
            if (_myIO.CreateDirectory(_filePath, _quotes))
            {
                _filePath += _quotes + "\\";
            }
        }
        else
        {
            _filePath += _quotes + "\\";
        }

        return _filePath;
    }

    public void LoadUploadDocument()
    {
        MyDatabase _db = new MyDatabase("GG_CRMDBConnectionString");
        string _spName = "sprocCXCRMNonGGCarFileUploadDetailSelectItemList";
        string Language = "EN";
        Int16 Renewal = 0;
        if (lblLangOption.Text == "1")
            Language = "TH";
        if (ddlApplicationType.Text == "REN" || ddlApplicationType.Text == "RNO")
        {
            Renewal = 1;
        }
       
        SortedList _spara = new SortedList();
        _spara.Add("@CECarId", Convert.ToInt64(txtCarId.Text));
        _spara.Add("@ProviderCompanyId", Convert.ToInt64(txtProviderId.Text));
        _spara.Add("@Language", Language);
        _spara.Add("@Renewal", Renewal);
        DataSet _dsUploadDocument = new DataSet();
        _dsUploadDocument = _db.GetDataSet(_spName, _spara);
        if (_dsUploadDocument != null && _dsUploadDocument.Tables.Count > 3 && _dsUploadDocument.Tables[3].Rows.Count > 0)
        {
            grvFileUpload.Visible = true;
            grvFileUpload.DataSource = _dsUploadDocument.Tables[3];
            grvFileUpload.DataBind();
            if (grvFileUpload.Rows.Count > 0)
            {
                divFileList.Visible = true;
                pnlUploadFileList.Visible = true;
            }
            else
            {
                divFileList.Visible = false;
                pnlUploadFileList.Visible = false;
            }
        }
        else
        {
            grvFileUpload.DataSource = null;
            grvFileUpload.DataBind();
            divFileList.Visible = false;
        }
    }

    public void ExportGridView(string fileName, Label lblContent)
    {
        string attachment = "attachment; filename=" + fileName + ".xls";
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/ms-excel";
        Response.Write(lblContent.Text);
        Response.End();
    }

    private string GetRandomNo()
    {
        string _RandomNo = "";
        int _randomlen = 6;
        Random random = new Random();
        for (int i = 0; i < _randomlen; i++)
        {
            _RandomNo += random.Next(0, 9).ToString();
        }
        return _RandomNo;
    }

    public void ClearFields()
    {
        txtStatus.Text = "TRUE";
        btnPayDecline.Visible = false;
        grvPayment.Enabled = true;
        pnlPaymentInput.Visible = true;
        btnPaySubmit.Text = Resources.General.Submit;
        lblLoadMessage.Text = string.Empty;
        lblPayError.Text = "";
        pnlCarDetails.Visible = false;
        //pnlUpload.Visible = false;
        pnlDetails.Visible = false;
        lblUpApplicantName.Text = "";
        lblUpInsurer.Text = "";
        lblUpPlanName.Text = "";
        lblUpPremium.Text = "";
        lblUpPremiumWD.Text = "";
        lblUpPremiumWOD.Text = "";
        txtProviderId.Text = "";
        //txtUserId.Text = "";
        txtCarModelYear.Text = "";
        txtCarMakeModel.Text = "";
        txtSumInsured.Text = "";
        txtInsurancePremium.Text = "";
        txtCTPL.Text = "";
        txtTotalPremium.Text = "";
        txtCurrentInsurer.Text = "";
        //txtDispalcement.Text = "";
        //txtWeight.Text = "";
        //txtNumberofSeat.Text = "";
        //txtEngineNumber.Text = "";
        txtChassisNumber.Text = "";
        txtPlateNumber.Text = "";
        txtRegistrationProvince.Text = "";
        ddlNCB.SelectedIndex = 0;
        txtInsuranceCompany.Text = "";
        txtPackage.Text = "";
        txtDriverFirst.Text = "";
        txtDriver1IDNo.Text = "";
        txtDriver1LicenseNo.Text = "";
        txtDriverTwo.Text = "";
        txtDriver2IDNo.Text = "";
        txtDriver2LicenseNo.Text = "";
        txtPrefix.Text = "";
        txtBeneficiary.Text = "";
        txtInsuredPerson.Text = "";
        txtContactNumber.Text = "";
        txtCurrentAddress.Text = "";
        txtSubDistrict.Text = "";
        txtStateProvince.Text = "";
        txtProvince.Text = "";
        txtPostalCode.Text = "";
        txtNewQuoteRefNo.Text = "";
        txtDriverId1.Text = "0";
        txtDriverId2.Text = "0";
        chkSameAddress.Checked = false;
        txtSameAddress.Text = "";
        txtSameAddrSubDistrict.Text = "";
        txtSameAddrStateProvince.Text = "";
        txtSameAddrProvince.Text = "";
        txtSameAddrPostalCode.Text = "";
        txtSameAddrName.Text = "";
        refSameAddrName.Enabled = false;
        refSameAddress.Enabled = false;
        refSameAddrSubDistrict.Enabled = false;
        refSameAddrStateProvince.Enabled = false;
        refSameAddrProvince.Enabled = false;
        refSameAddrPostalCode.Enabled = false;
    }

    public void LoadGarageType()
    {
        ddlGarageType.Items.Clear();
        ddlGarageType.Items.Add(new ListItem(Resources.General.Select, "-1"));
        ddlGarageType.Items.Add(new ListItem(Resources.CarInsurance.Garage_Authorized, "1"));
        ddlGarageType.Items.Add(new ListItem(Resources.CarInsurance.Garage_Dealer, "2"));
    }

    public void LoadInsuranceType()
    {
        ddlInsuranceType.Items.Clear();
        ddlInsuranceType.Items.Add(new ListItem(Resources.General.Select, "-1"));
        ddlInsuranceType.Items.Add(new ListItem(Resources.CarInsurance.Insurance_ClassOne, "10"));
        ddlInsuranceType.Items.Add(new ListItem(Resources.CarInsurance.Insurance_ClassOneLowCost, "11"));
        ddlInsuranceType.Items.Add(new ListItem(Resources.CarInsurance.Insurance_ClassTwoPlus, "21"));
        ddlInsuranceType.Items.Add(new ListItem(Resources.CarInsurance.Insurance_ClassTwo, "20"));
        ddlInsuranceType.Items.Add(new ListItem(Resources.CarInsurance.Insurance_ClassThreePlus, "31"));
        ddlInsuranceType.Items.Add(new ListItem(Resources.CarInsurance.Insurance_ClassThree, "30"));
    }

    public void LoadVehicleType()
    {
        ddlVehicleType.Items.Clear();
        ddlVehicleType.Items.Add(new ListItem(Resources.General.Select, "-1"));
        ddlVehicleType.Items.Add(new ListItem(Resources.CarInsurance.VehicleType_Private, "110"));
        ddlVehicleType.Items.Add(new ListItem(Resources.CarInsurance.VehicleType_Commercial, "210"));
    }

    public void LoadDate(DropDownList ddl)
    {
        string val = "";
        ddl.Items.Clear();
        for (int _date = 1; _date <= 31; _date++)
        {
            val = _date.ToString();
            if (_date < 10)
            {
                val = "0" + _date.ToString();
            }
            ddl.Items.Add(new ListItem(val, val));
        }
    }

    public void LoadMonth(DropDownList ddl)
    {
        string val = "";
        ddl.Items.Clear();
        
        string monthname = Resources.General.Select;
        for (int _month = 1; _month <= 12; _month++)
        {
            val = _month.ToString();
            if (_month < 10)
            {
                val = "0" + _month.ToString();
            }
            else
            {
                val = _month.ToString();
            }
            if (_month == 1)
            {
                monthname = Resources.MonthResource.January;
            }
            else if (_month == 2)
            {
                monthname = Resources.MonthResource.February;
            }
            else if (_month == 3)
            {
                monthname = Resources.MonthResource.March;
            }
            else if (_month == 4)
            {
                monthname = Resources.MonthResource.April;
            }
            else if (_month == 5)
            {
                monthname = Resources.MonthResource.May;
            }
            else if (_month == 6)
            {
                monthname = Resources.MonthResource.June;
            }
            else if (_month == 7)
            {
                monthname = Resources.MonthResource.July;
            }
            else if (_month == 8)
            {
                monthname = Resources.MonthResource.August;
            }
            else if (_month == 9)
            {
                monthname = Resources.MonthResource.September;
            }
            else if (_month == 10)
            {
                monthname = Resources.MonthResource.October;
            }
            else if (_month == 11)
            {
                monthname = Resources.MonthResource.November;
            }
            else if (_month == 12)
            {
                monthname = Resources.MonthResource.December;
            }
            
            ddl.Items.Add(new ListItem(monthname, val));
        }
    }

    public void LoadYear(DropDownList ddl, int start, int end)
    {
        string ddlval = "";
        string ddltxt = "";
        ddl.Items.Clear();
        for (int _year = start; _year <= end; _year++)
        {
            ddlval = _year.ToString();
            ddltxt = _year.ToString();
            if (lblLangOption.Text == "1")
            {
                ddltxt = (_year + 543).ToString();
            }
            ddl.Items.Add(new ListItem(ddltxt, ddlval));
        }
    }

    public void LoadOccupation()
    {
        DataTable dtOccupation = General.GetComboItem(Resources.CarInsurance.OccupationList, Resources.CarInsurance.OccupationSortBy, true);
        ddlOccupation.DataSource = dtOccupation;
        ddlOccupation.DataTextField = dtOccupation.Columns[0].ColumnName.ToString();
        ddlOccupation.DataValueField = dtOccupation.Columns[1].ColumnName.ToString();
        ddlOccupation.DataBind();
    }

    public void LoadFileUploadType()
    {
        string strKey = "";
        strKey = "EN.FileUploadType";
        if (lblLangOption.Text == "1")
        {
            strKey = "TH.FileUploadType";
        }
        DataTable dtFileUploadType = General.GetComboItem(strKey, true);
        ddlFileUploadType.DataSource = dtFileUploadType;
        ddlFileUploadType.DataTextField = dtFileUploadType.Columns[0].ColumnName.ToString();
        ddlFileUploadType.DataValueField = dtFileUploadType.Columns[1].ColumnName.ToString();
        ddlFileUploadType.DataBind();
        ddlFileUploadType.Items.Insert(0, new ListItem("Select", "-1"));
    }

    public void LoadDOB()
    {
        int intStartYear = dateTimeNow.Year - 90;
        int intEndYear = dateTimeNow.Year - 18;
        LoadDate(ddlDOBDay);
        LoadMonth(ddlDOBMonth);
        LoadYear(ddlDOBYear, intStartYear, intEndYear);

        LoadDate(ddlDriver1DOBDay);
        LoadMonth(ddlDriver1DOBMonth);
        LoadYear(ddlDriver1DOBYear, intStartYear, intEndYear);

        LoadDate(ddlDriver2DOBDay);
        LoadMonth(ddlDriver2DOBMonth);
        LoadYear(ddlDriver2DOBYear, intStartYear, intEndYear);
    }

    public void LoadCommanceDate()
    {
        int intStartYear = dateTimeNow.Year - 1;
        int intEndYear = dateTimeNow.Year + 2;
        LoadDate(ddlCommenceDay);
        LoadMonth(ddlCommenceMonth);
        LoadYear(ddlCommenceYear, intStartYear, intEndYear);
        LoadDate(ddlPolicyDay);
        LoadMonth(ddlPolicyMonth);
        LoadYear(ddlPolicyYear, intStartYear, intEndYear);
    }

    public void EnableOnOff(bool OnOff)
    {
        if (OnOff == true)
        {
            txtCarModelYear.ReadOnly = false;
            txtCarMakeModel.ReadOnly = false;
            txtCurrentInsurer.ReadOnly = false;
        }
        else if (OnOff == false)
        {
            txtCarModelYear.ReadOnly = true;
            txtCarMakeModel.ReadOnly = true;
            txtCurrentInsurer.ReadOnly = true;
        }
        ddlInsuranceType.Enabled = false;
        chkMile.Enabled = false;
        ddlVehicleType.Enabled = false;
        //ddlGarageType.Enabled = false;
        ddlCommenceDay.Enabled = OnOff;
        ddlCommenceMonth.Enabled = OnOff;
        ddlCommenceYear.Enabled = OnOff;

        ddlPolicyDay.Enabled = OnOff;
        ddlPolicyMonth.Enabled = OnOff;
        ddlPolicyYear.Enabled = OnOff;

        ddlCTPL.Enabled = false;
        

        ddlDOBDay.Enabled = OnOff;
        ddlDOBMonth.Enabled = OnOff;
        ddlDOBYear.Enabled = OnOff;
        ddlGender.Enabled = OnOff;
        ddlOccupation.Enabled = OnOff;
        ddlNamedDriver.Enabled = OnOff;
    }

    public void EnablePaymentOnOff()
    {
        if (chkRefund.Checked)
        {
            rfvPaymentType.Enabled = false;
            rfvPaymentOption.Enabled = false;
            rfvNoOfInstallments.Enabled = false;
            rfvIssuingBank.Enabled = false;
            rfvIssuingBank.Enabled = false;
            rfvCardType.Enabled = false;
            rfvBank.Enabled = false;

            //rfvCardHolder.Enabled = false;
            //rfvCardNo1.Enabled = false;
            //revCardNo1.Enabled = false;
            //rfvCardNo2.Enabled = false;
            //revCardNo2.Enabled = false;
            //rfvCardNo3.Enabled = false;
            //revCardNo3.Enabled = false;
            //rfvCardNo4.Enabled = false;
            //revCardNo4.Enabled = false;
            //rfvCardExpiryMonth.Enabled = false;
            //rfvCardExpiryYear.Enabled = false;
            //revCardExpiryMonth.Enabled = false;
            //revCardExpiryYear.Enabled = false;
            //csvCCExpiredValid.Enabled = false;
            //rfvCVV.Enabled = false;
            //revCVV.Enabled = false;
        }
        else
        {
            rfvPaymentType.Enabled = true;
            rfvPaymentOption.Enabled = true;
            rfvBank.Enabled = false;
            if (ddlPaymentType.Text == "CCOL" || ddlPaymentType.Text == "CCIP")
            {
                if (chkApprove.Checked)
                {
                    rfvNoOfInstallments.Enabled = false;
                    rfvIssuingBank.Enabled = false;
                    rfvIssuingBank.Enabled = false;
                    rfvCardType.Enabled = false;
                    //rfvCardHolder.Enabled = false;
                    //rfvCardNo1.Enabled = false;
                    //revCardNo1.Enabled = false;
                    //rfvCardNo2.Enabled = false;
                    //revCardNo2.Enabled = false;
                    //rfvCardNo3.Enabled = false;
                    //revCardNo3.Enabled = false;
                    //rfvCardNo4.Enabled = false;
                    //revCardNo4.Enabled = false;
                    //rfvCardExpiryMonth.Enabled = false;
                    //rfvCardExpiryYear.Enabled = false;
                    //revCardExpiryMonth.Enabled = false;
                    //revCardExpiryYear.Enabled = false;
                    //csvCCExpiredValid.Enabled = false;
                    //rfvCVV.Enabled = false;
                    //revCVV.Enabled = false;
                }
                else
                {
                    if (ddlPaymentOption.Text == "IP")
                    {
                        rfvNoOfInstallments.Enabled = true;
                        rfvIssuingBank.Enabled = true;
                    }
                    rfvIssuingBank.Enabled = true;
                    rfvCardType.Enabled = true;
                    //rfvCardHolder.Enabled = true;
                    //rfvCardNo1.Enabled = true;
                    //revCardNo1.Enabled = true;
                    //rfvCardNo2.Enabled = true;
                    //revCardNo2.Enabled = true;
                    //rfvCardNo3.Enabled = true;
                    //revCardNo3.Enabled = true;
                    //rfvCardNo4.Enabled = true;
                    //revCardNo4.Enabled = true;
                    //rfvCardExpiryMonth.Enabled = true;
                    //rfvCardExpiryYear.Enabled = true;
                    //revCardExpiryMonth.Enabled = true;
                    //revCardExpiryYear.Enabled = true;
                    //csvCCExpiredValid.Enabled = true;
                    //rfvCVV.Enabled = true;
                    //revCVV.Enabled = true;
                }
            }
            else
            {
                if (ddlPaymentType.Text == "BKTR")
                {
                    if (chkApprove.Checked)
                    {
                        rfvBank.Enabled = false;
                    }
                    else
                    {
                        rfvBank.Enabled = true;
                    }
                }
                rfvIssuingBank.Enabled = false;
                rfvCardType.Enabled = false;
                //rfvCardHolder.Enabled = false;
                //rfvCardNo1.Enabled = false;
                //revCardNo1.Enabled = false;
                //rfvCardNo2.Enabled = false;
                //revCardNo2.Enabled = false;
                //rfvCardNo3.Enabled = false;
                //revCardNo3.Enabled = false;
                //rfvCardNo4.Enabled = false;
                //revCardNo4.Enabled = false;
                //rfvCardExpiryMonth.Enabled = false;
                //rfvCardExpiryYear.Enabled = false;
                //revCardExpiryMonth.Enabled = false;
                //revCardExpiryYear.Enabled = false;
                //csvCCExpiredValid.Enabled = false;
                //rfvCVV.Enabled = false;
                //revCVV.Enabled = false;
            }
        }
    }

    //protected void csvCCExpiredValid_ServerValidate(object source, ServerValidateEventArgs args)
    //{
    //    txtCCExpiredValid.Text = "";
    //    txtCCExpiredValid.Text = "valid";
    //    Int32 _Year = Convert.ToInt32("20" + txtCardExpiryYear.Text); //ddlCardExpiryYear.Text
    //    Int32 _Month = Convert.ToInt32(txtCardExpiryMonth.Text); //ddlCardExpiryMonth.Text
    //    MySecurity _mysecurity = new MySecurity();
    //    if (_mysecurity.IsCreditCardExpiredDateValid(_Year, _Month))
    //    {
    //        args.IsValid = true;
    //    }
    //    else
    //    {
    //        args.IsValid = false;
    //    }
    //}


    private void ClearPayFields()
    {
        txtStatus.Text = "TRUE";
        btnPayDecline.Visible = false;
        grvPayment.Enabled = true;
        pnlPaymentInput.Visible = true;
        btnPaySubmit.Text = Resources.General.Submit;
        lblLoadMessage.Text = string.Empty;
        txtPaymentId.Text = "0";
        EnableDisable();
        lblPayError.Text = "";
        txtAmount.Text = "";

        //Yui@05/01/2014
        ddlPaymentOption.Enabled = true; //false;
        ddlPaymentOption_SelectedIndexChanged(null, null);
       
        ddlPaymentType.SelectedIndex = 0;
        ddlPaymentType_SelectedIndexChanged(null, null);
        txtIssuingBank.Text = "";
        txtPaymentRefNo.Text = "";
        ddlCardType.SelectedIndex = 0;

        //txtCardHolder.Text = "";
        //txtCardNo1.Text = "";
        //txtCardNo2.Text = "";
        //txtCardNo3.Text = "";
        //txtCardNo4.Text = "";
        //txtCardExpiryMonth.Text = "";
        //txtCardExpiryYear.Text = "";
        //txtCVV.Text = "000";

        chkRefund.Checked = false;
        chkApprove.Checked = false;
        chkRefund.Enabled = true;
        chkApprove.Enabled = false;
        txtAmount.ReadOnly = false;

        //divCC.Visible = false;
        //rfvCVV.Enabled = true;
        //revCVV.Enabled = true;
        
        //pnlAmountwithInterest.Visible = false;
        lblAmountwithInterest.Text = "";
        lblInstallmentList.Text = "";
        txtAgentRemarks.Text = "";
    }

    private bool ChackPayValidate()
    {
        bool _IsValid = true;
        if (rfvAmount.IsValid == false)
        {
            _IsValid = false;
        }
        else if (revAmount.IsValid == false)
        {
            _IsValid = false;
        }
        else if (rfvPaymentOption.IsValid == false)
        {
            _IsValid = false;
        }
        else if (rfvPaymentType.IsValid == false)
        {
            _IsValid = false;
        }
        else if (rfvIssuingBank.IsValid == false)
        {
            _IsValid = false;
        }
        else if (rfvCardType.IsValid == false)
        {
            _IsValid = false;
        }
        //else if (rfvCardHolder.IsValid == false)
        //{
        //    _IsValid = false;
        //}
        //else if (rfvCardNo1.IsValid == false)
        //{
        //    _IsValid = false;
        //}
        //else if (revCardNo1.IsValid == false)
        //{
        //    _IsValid = false;
        //}
        //else if (rfvCardNo2.IsValid == false)
        //{
        //    _IsValid = false;
        //}
        //else if (revCardNo2.IsValid == false)
        //{
        //    _IsValid = false;
        //}
        //else if (rfvCardNo3.IsValid == false)
        //{
        //    _IsValid = false;
        //}
        //else if (revCardNo3.IsValid == false)
        //{
        //    _IsValid = false;
        //}
        //else if (rfvCardNo4.IsValid == false)
        //{
        //    _IsValid = false;
        //}
        //else if (revCardNo4.IsValid == false)
        //{
        //    _IsValid = false;
        //}
        //else if (rfvCardExpiryMonth.IsValid == false)
        //{
        //    _IsValid = false;
        //}
        //else if (rfvCardExpiryYear.IsValid == false)
        //{
        //    _IsValid = false;
        //}
        //else if (revCardExpiryMonth.IsValid == false)
        //{
        //    _IsValid = false;
        //}
        //else if (revCardExpiryYear.IsValid == false)
        //{
        //    _IsValid = false;
        //}
        //else if (csvCCExpiredValid.IsValid == false)
        //{
        //    _IsValid = false;
        //}
        //else if (rfvCVV.IsValid == false)
        //{
        //    _IsValid = false;
        //}
        //else if (revCVV.IsValid == false)
        //{
        //    _IsValid = false;
        //}
        else if (rfvPaymentRefNo.IsValid == false)
        {
            _IsValid = false;
        }
        return _IsValid;
    }

    private Int16 ValidatePaymentsSubmission(string PaymentOption)
    {
        Int16 _result = 0;
        try
        {
            DataSet _dsPaymentList = new DataSet();
            _dsPaymentList = GetApprovedPayments();
            if (_dsPaymentList != null && _dsPaymentList.Tables.Count > 0 && _dsPaymentList.Tables[0].Rows.Count > 0 && chkRefund.Checked)
            {
                _result = 1;
                decimal _balance = 0;
                if(!decimal.TryParse(txtBalanceAmount.Text, out _balance))
                {
                    _balance = 0;
                }
                if (_balance < 0)
                {
                    _result = 0;
                }
                else if (chkApprove.Checked)
                {
                    _result = 0;
                }
            }
            else if (_dsPaymentList != null && _dsPaymentList.Tables.Count > 0 && _dsPaymentList.Tables[0].Rows.Count > 0 && PaymentOption == "FP")
            {
                if (_dsPaymentList.Tables[0].Rows[0]["ApproveType"].ToString() == "1")
                    _result = 2;
            }
            else if (_dsPaymentList != null && _dsPaymentList.Tables.Count > 6 && _dsPaymentList.Tables[6].Rows.Count > 0 && PaymentOption == "IP")
            {
                _result = 3;
            }
            else if (_dsPaymentList != null && _dsPaymentList.Tables.Count > 0 && _dsPaymentList.Tables[0].Rows.Count > 0 && PaymentOption == "IP" && chkApprove.Checked == false && txtPaymentId.Text == "0")
            {
                _result = 2;
            }
        }
        catch (Exception ex)
        {
        }
        return _result;
    }

    public string GenerateNonGGExcel(Int64 CECarId, Int64 ProviderId, string FilePath, string FileName)
    {
        string _returnFilePath = "";
        Label lblContent = new Label();
        StringBuilder strText = new StringBuilder("");
        strText.Append("<table><tr><td colspan='2'><h3>ประกันภัยรถยนต์ - แบบฟอร์ม</h3></td></tr></table>");
        DataSet _dsApplication = new DataSet();
        NonGGPackageDB _nonggpackagedb = new NonGGPackageDB();
        _dsApplication = _nonggpackagedb.GetNonGGApplication(CECarId, ProviderId, 0);
        string _html = "";
        if (_dsApplication.Tables[0].Rows.Count > 0)
        {

            #region Variable Declaration

            string strSql = "";
            MyDatabase _db = new MyDatabase();
            string Title, Name, DOB, Gender, Occupation, ContactNo, Email,CitizenIDnumber, PresentAddress, SubDistrict, District, Province, PostalCode, Insurer, Package, NoOfDriver;
            string InsuranceType, GarageType, CarModelYear, CarMakeModel, Beneficiary, VehicleType, SumInsured, NCB;
            string CurrentInsurer, CarPlate, CarPlateProvince, EngineNumber, ChassisNumber, AddDrivers, CommencementDate, ComExtDate;
            string Premium, CTPL, CTPLAmount, TotalPremium, PaymentType, QuoteRefNo, Payment, ApplicationDate, TotalCollectedPremium, CustomerName;
            string CustomerType, CTPLStart, ProviderPremium, strLastYearRefNo, strLastYearPolicyNo, strTitle, ModificationAmount;
            string MailingAddress, MailingSubDistrict, MailingDistrict, MailingProvince, MailingPostalCode, MailingName;
            
            float _GrossPremium = 0.0f;

            strLastYearRefNo = string.Empty;
            strLastYearPolicyNo = string.Empty;
            Title = ""; Name = ""; DOB = ""; Gender = ""; Occupation = ""; ContactNo = ""; Email = ""; CitizenIDnumber = ""; PresentAddress = ""; SubDistrict = ""; District = "";
            Province = ""; PostalCode = ""; Insurer = ""; Package = ""; NoOfDriver = ""; InsuranceType = ""; GarageType = ""; CarModelYear = "";
            CarMakeModel = ""; Beneficiary = ""; VehicleType = ""; SumInsured = ""; NCB = "";
            CurrentInsurer = ""; CarPlate = ""; CarPlateProvince = ""; EngineNumber = ""; ChassisNumber = ""; ComExtDate = "";
            AddDrivers = ""; CommencementDate = ""; Premium = ""; CTPL = ""; CTPLAmount = ""; TotalPremium = ""; PaymentType = ""; CTPLStart = "";
            QuoteRefNo = ""; Payment = ""; ApplicationDate = ""; TotalCollectedPremium = ""; CustomerName = ""; CustomerType = ""; ProviderPremium = "";
            ModificationAmount = string.Empty;
            MailingAddress = ""; MailingSubDistrict = ""; MailingDistrict = ""; MailingProvince = ""; MailingPostalCode = ""; MailingName = "";
            //For Driver
            string DriverName1, DriverDOB1, DriverName2, DriverDOB2, Driver1LicenseNo, Driver2LicenseNo, Driver1IDNo, Driver2IDNo;
            DriverName1 = ""; DriverDOB1 = ""; DriverName2 = ""; DriverDOB2 = ""; Driver1LicenseNo = ""; Driver2LicenseNo = "";
            Driver1IDNo = ""; Driver2IDNo = "";

            #endregion

            #region Assign Values
            strTitle = "รายละเอียดผู้ทำประกัน";
            if (ddlApplicationType.Text == "REN")
            {
                strTitle += " - ต่ออายุ";
            }
            else if (ddlApplicationType.Text == "CHB")
            {
                strTitle += " - เปลี่ยนโบรกเกอร์";
            }
            if (txtUserId.Text != string.Empty && txtUserId.Text != "0" && txtCarId.Text != string.Empty && txtCarId.Text != "0")
            {
                
                strLastYearRefNo = lblLastYearRefNo.Text;
                strSql = "SELECT Info2 FROM tblNonGGCarMoreDetails WHERE Info2 IS NOT NULL AND LEN(Info2) > 0 AND CECarId = " + txtCarId.Text.Trim() + " AND RefCEUserId = " + txtUserId.Text.Trim();
                DataTable _SelectItemResult = _db.GetDataTable(strSql);
                if (_SelectItemResult != null && _SelectItemResult.Rows.Count > 0)
                {
                    if (_SelectItemResult.Rows[0]["Info2"] != DBNull.Value)
                    {
                        strLastYearPolicyNo = _SelectItemResult.Rows[0]["Info2"].ToString();
                    }
                }
            }
            else
            {
                strLastYearRefNo = lblLastYearRefNo.Text;
            }
            Email = _dsApplication.Tables[0].Rows[0]["Email"].ToString();
            Title = _dsApplication.Tables[0].Rows[0]["Title"].ToString();
            Name = _dsApplication.Tables[0].Rows[0]["Name"].ToString();
            CustomerName = _dsApplication.Tables[0].Rows[0]["CustomerName"].ToString();
            CustomerType = _dsApplication.Tables[0].Rows[0]["CustomerTypeTH"].ToString();
            DOB = _dsApplication.Tables[0].Rows[0]["DOB"].ToString();
            Gender = _dsApplication.Tables[0].Rows[0]["Gender"].ToString();
            Occupation = _dsApplication.Tables[0].Rows[0]["Occupation"].ToString();
            ContactNo = _dsApplication.Tables[0].Rows[0]["ContactNo"].ToString();
            Beneficiary = _dsApplication.Tables[0].Rows[0]["Beneficiary"].ToString();
            if (_dsApplication.Tables[0].Rows[0]["IdentificationNo"] != DBNull.Value)
            {
                CitizenIDnumber = _dsApplication.Tables[0].Rows[0]["IdentificationNo"].ToString();
            }
            PresentAddress = _dsApplication.Tables[0].Rows[0]["PresentAddress"].ToString();
            SubDistrict = _dsApplication.Tables[0].Rows[0]["SubDistrict"].ToString();
            District = _dsApplication.Tables[0].Rows[0]["District"].ToString();
            Province = _dsApplication.Tables[0].Rows[0]["Province"].ToString();
            PostalCode = _dsApplication.Tables[0].Rows[0]["PostalCode"].ToString();

            if (_dsApplication.Tables[0].Rows[0]["IsMailingAddressDiff"] != DBNull.Value &&
                _dsApplication.Tables[0].Rows[0]["IsMailingAddressDiff"].ToString() == "True")
            {
                MailingAddress = _dsApplication.Tables[0].Rows[0]["MailingAddress"].ToString();
                MailingSubDistrict = _dsApplication.Tables[0].Rows[0]["MailingSubDistrict"].ToString();
                MailingDistrict = _dsApplication.Tables[0].Rows[0]["MailingDistrict"].ToString();
                MailingProvince = _dsApplication.Tables[0].Rows[0]["MailingProvince"].ToString();
                MailingPostalCode = _dsApplication.Tables[0].Rows[0]["MailingPostalCode"].ToString();
                MailingName = _dsApplication.Tables[0].Rows[0]["MailingName"].ToString();
            }

            Insurer = _dsApplication.Tables[0].Rows[0]["CompanyName"].ToString();
            Package = _dsApplication.Tables[0].Rows[0]["Package"].ToString();
            NoOfDriver = _dsApplication.Tables[0].Rows[0]["NoOfDriver"].ToString();
            if (NoOfDriver.ToString() == "0")
            {
                AddDrivers = "No";
            }
            else
            {
                AddDrivers = "Yes";
            }
            InsuranceType = _dsApplication.Tables[0].Rows[0]["InsuranceType"].ToString();
            GarageType = _dsApplication.Tables[0].Rows[0]["GarageType"].ToString();
            CarModelYear = _dsApplication.Tables[0].Rows[0]["CarModelYear"].ToString();
            CarMakeModel = _dsApplication.Tables[0].Rows[0]["CarMakeModel"].ToString();
           
            EngineNumber = _dsApplication.Tables[0].Rows[0]["EngineNumber"].ToString();
            ChassisNumber = _dsApplication.Tables[0].Rows[0]["ChassisNumber"].ToString();
            Beneficiary = _dsApplication.Tables[0].Rows[0]["Beneficiary"].ToString();
            VehicleType = _dsApplication.Tables[0].Rows[0]["VehicleType"].ToString();
            SumInsured = _dsApplication.Tables[0].Rows[0]["SumInsured"].ToString();
            NCB = _dsApplication.Tables[0].Rows[0]["NCB"].ToString();
            CurrentInsurer = _dsApplication.Tables[0].Rows[0]["CurrentInsurer"].ToString();
            CarPlate = _dsApplication.Tables[0].Rows[0]["CarPlate"].ToString();
            CarPlateProvince = _dsApplication.Tables[0].Rows[0]["ProvinceRegistration"].ToString();
           
            CommencementDate = _dsApplication.Tables[0].Rows[0]["CommencementDate"].ToString();
            Premium = _dsApplication.Tables[0].Rows[0]["Premium"].ToString();

            CTPL = _dsApplication.Tables[0].Rows[0]["CTPL"].ToString();
            CTPLAmount = _dsApplication.Tables[0].Rows[0]["CTPLAmount"].ToString();
            CTPLStart = _dsApplication.Tables[0].Rows[0]["CTPLStart"].ToString();
            TotalPremium = _dsApplication.Tables[0].Rows[0]["TotalPremium"].ToString();
            TotalCollectedPremium = _dsApplication.Tables[0].Rows[0]["TotalCollectedPremium"].ToString();
            PaymentType = _dsApplication.Tables[0].Rows[0]["PaymentType"].ToString();
            QuoteRefNo = _dsApplication.Tables[0].Rows[0]["QuoteRefNo"].ToString();
            Payment = _dsApplication.Tables[0].Rows[0]["Payment"].ToString();
            ApplicationDate = _dsApplication.Tables[0].Rows[0]["ApplicationDate"].ToString();
            
            if (_dsApplication.Tables[0].Rows[0]["GrossPremium"] != DBNull.Value && _dsApplication.Tables[0].Rows[0]["GrossPremium"].ToString() != string.Empty)
            {
                _GrossPremium = Convert.ToSingle(_dsApplication.Tables[0].Rows[0]["GrossPremium"].ToString());
            }
            ProviderPremium = GetProviderPremium(_GrossPremium, CTPL.ToUpper(), CTPLAmount);

            if (_dsApplication.Tables[0].Rows[0]["ModificationAmount"] != DBNull.Value && _dsApplication.Tables[0].Rows[0]["ModificationAmount"].ToString() != string.Empty)
            {
                ModificationAmount = _dsApplication.Tables[0].Rows[0]["ModificationAmount"].ToString();
            }

            if (AddDrivers == "Yes")
            {
                if (_dsApplication.Tables[1].Rows.Count > 0)
                {
                    if (Convert.ToInt16(NoOfDriver) > 0)
                    {
                        DriverName1 = _dsApplication.Tables[1].Rows[0]["FullName"].ToString();
                        DriverDOB1 = _dsApplication.Tables[1].Rows[0]["DOB"].ToString();
                        Driver1IDNo = _dsApplication.Tables[1].Rows[0]["IDNo"].ToString();
                        Driver1LicenseNo = _dsApplication.Tables[1].Rows[0]["DrivingLicenseNumber"].ToString();
                    }
                    if (Convert.ToInt16(NoOfDriver) > 1)
                    {

                        DriverName2 = _dsApplication.Tables[1].Rows[1]["FullName"].ToString();
                        DriverDOB2 = _dsApplication.Tables[1].Rows[1]["DOB"].ToString();
                        Driver2IDNo = _dsApplication.Tables[1].Rows[1]["IDNo"].ToString();
                        Driver2LicenseNo = _dsApplication.Tables[1].Rows[1]["DrivingLicenseNumber"].ToString();
                    }
                }
            }

            //Renew Ext Com Date
            MyDatabase _myDb = new MyDatabase();
            string _strSelect = "SELECT CD.Dinfo2 "
                    + " FROM tblCarPolicy CP INNER JOIN tblCarDetailTH CD ON CD.CarId = CP.CECarId "
                    + " WHERE CP.RefCEUserId = " + txtUserId.Text.Trim() + " AND CP.CECarId= " + txtCarId.Text.Trim();
            object _extDate = _myDb.ExecuteScalarSqlStatement(_strSelect);
            if (_extDate != null && _extDate.ToString() != "")
            {
                ComExtDate = Convert.ToDateTime(_extDate).ToString("dd-MMM-yyyy");
            }
            //*****************

            #endregion

            #region Generate Excel File

            string pType = "";
            if (_dsApplication.Tables[2] != null && _dsApplication.Tables[2].Rows.Count > 0)
            {
                pType = _dsApplication.Tables[2].Rows[0]["PaymentType"].ToString();
                if (pType.Trim() == "CHINS") pType = " (c)";
            }

            _html += "<html><body><table width='60%' cellpadding='1' cellspacing='1' border='1' style='font-family:Microsoft Sans Serif; font-size: 11pt;'>";
            if (ddlApplicationType.Text == "REN")
            {
                _html += "<tr><td width='20%' align='left' colspan='2'><b>" + strTitle + pType + "</b></td></tr>";
                _html += "<tr><td width='250' align='left'><b>เลขที่อ้างอิงปีที่แล้ว</b></td><td  align='left'>" + strLastYearRefNo.ToString() + "</td></tr>";
                _html += "<tr><td width='250' align='left'><b>เลขที่กรมธรรม์ปีที่แล้ว</b></td><td  align='left'>" + strLastYearPolicyNo.ToString() + "</td></tr>";
            }
            else if (ddlApplicationType.Text == "CHB")
            {
                _html += "<tr><td width='20%' align='left' colspan='2'><b>" + strTitle + pType + "</b></td></tr>";
                _html += "<tr><td width='250' align='left'><b>เลขที่กรมธรรม์ปีที่แล้ว</b></td><td  align='left'>" + strLastYearPolicyNo.ToString() + "</td></tr>";
            }
            else
            {
                //CHINS
                _html += "<tr><td width='20%' align='left' colspan='2'><b>รายละเอียดผู้ทำประกัน" + pType + "</b></td></tr>";
            }

            _html += "<tr><td width='250' align='left'><b>ประเภทลูกค้า</b></td><td width='350' align='left'>" + CustomerType + "</td></tr>";
            _html += "<tr><td width='250' align='left'><b>คำนำหน้า</b></td><td  align='left'>" + Title + "</td></tr>";
            _html += "<tr><td width='250' align='left'><b>ชื่อผู้ทำประกัน</b></td><td  align='left'>" + Name + "</td></tr>";
            _html += "<tr><td width='250' align='left'><b>วันเกิด</b></td><td style='mso-number-format:dd\\-mmm\\-yyyy'  align='left'>" + DOB + "</td></tr>";
            _html += "<tr><td width='250' align='left'><b>เพศ</b></td><td  align='left'>" + Gender + "</td></tr>";
            _html += "<tr><td width='250' align='left'><b>อาชีพ</b></td><td  align='left'>" + Occupation + "</td></tr>";
            _html += "<tr><td width='250' align='left'><b>เบอร์ติดต่อ</b></td><td style='mso-number-format:\\@' align='left'>" + ContactNo + "</td></tr>";
            _html += "<tr><td width='250' align='left'><b>เลขที่บัตรประชาชน</b></td><td style='mso-number-format:\\@' align='left'>" + CitizenIDnumber + "</td></tr>";
            _html += "<tr><td width='250' align='left'><b>ที่อยู่ปัจจุบัน</b></td><td  align='left'>" + PresentAddress + "</td></tr>";
            _html += "<tr><td width='250' align='left'><b>แขวง/ตำบล</b></td><td  align='left'>" + SubDistrict + "</td></tr>";
            _html += "<tr><td width='250' align='left'><b>เขต/อำเภอ</b></td><td  align='left'>" + District + "</td></tr>";
            _html += "<tr><td width='250' align='left'><b>จังหวัด</b></td><td  align='left'>" + Province + "</td></tr>";
            _html += "<tr><td width='250' align='left'><b>รหัสไปรษณีย์</b></td><td  align='left'>" + PostalCode + "</td></tr>";
            _html += "<tr><td width='250' align='left'><b>บริษัทประกัน</b></td><td  align='left'>" + Insurer + "</td></tr>";
            _html += "<tr><td width='250' align='left'><b>แพกเก็จ</b></td><td  align='left'>" + Package + "</td></tr>";

            _html += "<tr><td width='250' align='left'><b>ระบุผู้ขับขี่</b></td><td  align='left'>" + AddDrivers + "</td></tr>";
            if (AddDrivers == "Yes")
            {
                _html += "<tr><td width='250' align='left'><b>จำนวนผู้ขับขี่</b></td><td  align='left'>" + NoOfDriver + "</td></tr>";
            }
            if (Convert.ToInt16(NoOfDriver) > 0)
            {
                _html += "<tr><td width='250' align='left'><b>วันเกิด ผู้ขับขี่คนที่ 1</b></td><td  style='mso-number-format:dd\\-mmm\\-yyyy' align='left'>" + DriverDOB1 + "</td></tr>";
                _html += "<tr><td width='250' align='left'><b>ผู้ขับขี่คนที่ 1</b></td><td  align='left'>" + DriverName1 + "</td></tr>";
                _html += "<tr><td width='250' align='left'><b>ผู้ขับขี่คนที่ 1 เลขที่บัตรประชาชน</b></td><td style='mso-number-format:\\@' align='left'>" + Driver1IDNo + "</td></tr>";
                _html += "<tr><td width='250' align='left'><b>ผู้ขับขี่คนที่ 1 เลขที่ใบขับขี่</b></td><td  align='left'>" + Driver1LicenseNo + "</td></tr>";
            }
            if (Convert.ToInt16(NoOfDriver) > 1)
            {
                _html += "<tr><td width='250' align='left'><b>วันเกิด ผู้ขับขี่คนที่ 2</b></td><td  style='mso-number-format:dd\\-mmm\\-yyyy' align='left'>" + DriverDOB2 + "</td></tr>";
                _html += "<tr><td width='250' align='left'><b>ผู้ขับขี่คนที่ 2</b></td><td  align='left'>" + DriverName2 + "</td></tr>";
                _html += "<tr><td width='250' align='left'><b>ผู้ขับขี่คนที่ 2 เลขที่บัตรประชาชน</b></td><td style='mso-number-format:\\@' align='left'>" + Driver2IDNo + "</td></tr>";
                _html += "<tr><td width='250' align='left'><b>ผู้ขับขี่คนที่ 2 เลขที่ใบขับข</b></td><td  align='left'>" + Driver2LicenseNo + "</td></tr>";
            }
            //Yui@22/01/2015
            if (!chkMile.Checked)
                _html += "<tr><td width='250' align='left'><b>ประเภทประกัน</b></td><td  align='left'>" + InsuranceType + "</td></tr>";
            else
                _html += "<tr><td width='250' align='left'><b>ประเภทประกัน</b></td><td  align='left'>" + InsuranceType + " (ตามไมล์)</td></tr>";

            _html += "<tr><td width='250' align='left'><b>ประเภทอู่</b></td><td  align='left'>" + GarageType + "</td></tr>";
            _html += "<tr><td width='250' align='left'><b>ปีของรถ</b></td><td  align='left'>" + CarModelYear + "</td></tr>";
            _html += "<tr><td width='250' align='left'><b>รุ่น</b></td><td  align='left'>" + CarMakeModel + "</td></tr>";
            _html += "<tr><td width='250' align='left'><b>ผู้รับผลประโยชน์</b></td><td  align='left'>" + Beneficiary + "</td></tr>";
            _html += "<tr><td width='250' align='left'><b>ประเภทรถ</b></td><td  align='left'>" + VehicleType + "</td></tr>";
            _html += "<tr><td width='250' align='left'><b>ทุนประกัน</b></td><td style='mso-number-format:\\#\\,\\#\\#0\\.00'  align='left'>" + SumInsured + "</td></tr>";
            _html += "<tr><td width='250' align='left'><b>ส่วนลด NCB</b></td><td  align='left'>" + NCB + "</td></tr>";
            if (ModificationAmount.ToString() != string.Empty && ModificationAmount.ToString() != "")
            {
                _html += "<tr><td width='250' align='left'><b>อุปกรณ์หรือการปรับเปลี่ยนค่าใช้จ่าย</b></td><td  align='left'>" + ModificationAmount + "</td></tr>";
            }
            _html += "<tr><td width='250' align='left'><b>บริษัทประกันปัจจุบัน</b></td><td  align='left'>" + CurrentInsurer + "</td></tr>";
            _html += "<tr><td width='250' align='left'><b>ทะเบียนรถ</b></td><td  align='left'>" + CarPlate + "</td></tr>";
            _html += "<tr><td width='250' align='left'><b>จังหวัดที่จดทะเบียน</b></td><td  align='left'>" + CarPlateProvince + "</td></tr>";
            _html += "<tr><td width='250' align='left'><b>หมายเลขเครื่อง</b></td><td  align='left'>" + EngineNumber + "</td></tr>";
            _html += "<tr><td width='250' align='left'><b>หมายเลข Chassis</b></td><td  align='left'>" + ChassisNumber + "</td></tr>";
            _html += "<tr><td width='250'  align='left'><b>วันเริ่มคุ้มครอง (ภาคสมัครใจ)</b></td><td style='mso-number-format:dd\\-mmm\\-yyyy'  align='left'>" + CommencementDate + "</td></tr>";
            if (ComExtDate != "")
            {
                _html += "<tr><td width='250'  align='left'><b>ขยายถึงวันที่</b></td><td style='mso-number-format:dd\\-mmm\\-yyyy'  align='left'>" + ComExtDate + "</td></tr>";
            }
            _html += "<tr><td width='250' align='left'><b>เบี้ยประกันภาคสมัครใจ</b></td><td style='mso-number-format:\\#\\,\\#\\#0\\.00' align='left'>" + _GrossPremium.ToString() + "</td></tr>";
            _html += "<tr><td width='250' align='left'><b>ซื้อ พ.ร.บ. หรือไม่</b></td><td  align='left'>" + CTPL + "</td></tr>";
            if (CTPL == "Yes")
            {
                _html += "<tr><td width='250' align='left'><b>เบี้ย พ.ร.บ.</b></td><td style='mso-number-format:\\#\\,\\#\\#0\\.00'  align='left'>" + CTPLAmount + "</td></tr>";
            }
            else
            {
                _html += "<tr><td width='250' align='left'><b>เบี้ย พ.ร.บ.</b></td><td align='left'>-</td></tr>";
            }
            _html += "<tr><td width='250'  align='left'><b>วันที่ พ.ร.บ.เริ่มคุ้มครอง</b></td><td style='mso-number-format:dd\\-mmm\\-yyyy'  align='left'>" + CTPLStart + "</td></tr>";
            _html += "<tr><td width='250' align='left'><b>เบี้ยประกันรวมทั้งหมด</b></td><td style='mso-number-format:\\#\\,\\#\\#0\\.00' align='left'>" + ProviderPremium + "</td></tr>";
            _html += "<tr><td width='250' align='left'><b>วันที่ทำรายการ</b></td><td style='mso-number-format:dd\\/mm\\/yyyy\\ hh\\:mm\\' align='left'>" + dateTimeNow.ToString("dd/MM/yyyy hh:mm", new System.Globalization.CultureInfo("en-US")) + "</td></tr>"; //ตาม วัน/เวลา ที่ปรากฎในอีเมล์

            if (MailingAddress.Trim() != "")
            {
                _html += "<tr><td width='250' align='left'><b>ชื้อผู้รับ</b></td><td  align='left'>" + MailingName + "</td></tr>";
                _html += "<tr><td width='250' align='left'><b>ที่อยู่ที่จัดส่ง</b></td><td  align='left'>" + MailingAddress + "</td></tr>";
                _html += "<tr><td width='250' align='left'><b>แขวง/ตำบล</b></td><td  align='left'>" + MailingSubDistrict + "</td></tr>";
                _html += "<tr><td width='250' align='left'><b>เขต/อำเภอ</b></td><td  align='left'>" + MailingDistrict + "</td></tr>";
                _html += "<tr><td width='250' align='left'><b>จังหวัด</b></td><td  align='left'>" + MailingProvince + "</td></tr>";
                _html += "<tr><td width='250' align='left'><b>รหัสไปรษณีย์</b></td><td  align='left'>" + MailingPostalCode + "</td></tr>";
            }

            _html += "</table></body></html>";
            #endregion

            lblContent.Text = _html;
            MyIO myio = new MyIO();

            string[] filecontent = new string[1];
            filecontent[0] = lblContent.Text.ToString();

            myio.WriteNewFile(FilePath, FileName + ".xls", filecontent);
            _returnFilePath = FilePath + FileName + ".xls";
        }
        return _returnFilePath;
    }

    public Int16 AmountExceedValid(Int16 Process)
    {
        string i = txtTotalRefundAmount.Text;
        Int16 _IsValid = 1;
        float Premium = 0;
        float Collected = 0;
        float Amount = 0;
        float Refund = 0;
        float Balance = 0;
        
        if (txtFinalPrice.Text != "") //20 Jun 2013
            Premium = Convert.ToSingle(txtFinalPrice.Text); //20 Jun 2013
        if (txtTotalCollectedAmount.Text != "")
            Collected = Convert.ToSingle(txtTotalCollectedAmount.Text);
        if (txtAmount.Text != "")
            Amount = Convert.ToSingle(txtAmount.Text);
        if (txtTotalRefundAmount.Text != "")
            Refund = Convert.ToSingle(txtTotalRefundAmount.Text);
        if (txtBalanceAmount.Text != "")
            Balance = Convert.ToSingle(txtBalanceAmount.Text);
        if (Process == 1)
        {
            if (chkApprove.Checked == false)
            {
                if (chkRefund.Checked)
                {
                    
                    if (Collected < (Amount))
                    {
                        _IsValid = 2;
                    }
                }
                else
                {
                    if (txtPaymentId.Text == "0")
                    {
                        float _calAmount = Collected + Amount;//20 Jun 2013

                        if (Premium < _calAmount)
                        {
                            _IsValid = 3;
                        }
                        else if (Amount > Balance)
                        {
                            _IsValid = 3;
                        }


                        if (Premium == _calAmount)
                        {
                            _IsValid = 1;
                        }
                    }
                }
            }
        }
        if (Process == 2)
        {
            _IsValid = 0;
            DataSet _dsPaymentAmount = new DataSet();
            _dsPaymentAmount = GetPaymentAmounts();
            if (_dsPaymentAmount != null && _dsPaymentAmount.Tables.Count > 0 && _dsPaymentAmount.Tables[0].Rows.Count > 0)
            {
                Premium = 0;
                Collected = 0;
                if (_dsPaymentAmount.Tables[0].Rows[0]["PremiumAmount"].ToString() != null && _dsPaymentAmount.Tables[0].Rows[0]["PremiumAmount"].ToString() != "")
                    Premium = Convert.ToSingle(_dsPaymentAmount.Tables[0].Rows[0]["PremiumAmount"].ToString());
                if (_dsPaymentAmount.Tables[0].Rows[0]["CollectedAmount"].ToString() != null && _dsPaymentAmount.Tables[0].Rows[0]["CollectedAmount"].ToString() != "")
                    Collected = Convert.ToSingle(_dsPaymentAmount.Tables[0].Rows[0]["CollectedAmount"].ToString());
                if (Premium > 0 && Premium == Collected)
                {
                    _IsValid = 1;
                }
            }
        }
        if (Process == 3)
        {
            if (txtOnlineAmount.Text != "")
            {
                Amount = Convert.ToSingle(txtOnlineAmount.Text);
            }

            float _calAmount = (Collected - Refund) + Amount;

            
            if (Premium < _calAmount)
            {
                _IsValid = 4;
            }
            else if (Amount > Balance)
            {
                _IsValid = 4;
            }

        }
        return _IsValid;
    }

    public DataSet GetTransaction(string QuoteRefNo, Int16 TransactionTypeId)
    {
        DataSet _dsTransaction = new DataSet();
        TransactionDB _transactiondb = new TransactionDB();
        _dsTransaction = _transactiondb.GetTransaction(QuoteRefNo, TransactionTypeId);
        return _dsTransaction;
    }

    public bool SubmitPaymentPermission()
    {
        bool _Valid = true;
        if (txtPaymentId.Text != "" && txtPaymentId.Text != "0" && chkApprove.Checked && Session[CE.Global.General.UserRole] != null && Session[CE.Global.General.UserRole].ToString() != "300")
        {
            _Valid = false;
        }
        if (lblMailingStatus.Text != string.Empty && lblMailingStatus.Text == "1")
        {
            _Valid = false;
        }
        return _Valid;
    }

    public string GetColor(string ApproveType)
    {
        string color = "red";
        if (ApproveType == "1")
        {
            color = "green";
        }
        return color;
    }

    public void LoadLableColor()
    {
        try
        {
            DataSet _dsPayment = new DataSet();
            DateTime _PremiumDate = dateTimeNow;
            DateTime _PremiumWDDate = dateTimeNow;
            DateTime _CurrentDate = dateTimeNow;
            TimeSpan ts;
            Int32 days = 0;
            Int32 noofrecords = 0;
            txtIsWD.Text = "1";
            Int64 Provider = 0;
            Int32 CoverType = 10;
            string PaymentOption = "FP";

            _dsPayment = GetApprovedPayments();// GetBrokerPremium();
            if (_dsPayment != null && _dsPayment.Tables.Count > 14 && _dsPayment.Tables[14].Rows.Count > 0)
            {
                txtNoOfRecords.Text = _dsPayment.Tables[14].Rows.Count.ToString();
                if (!Int32.TryParse(txtNoOfRecords.Text, out noofrecords))
                {
                    noofrecords = 0;
                }
            }

            if (_dsPayment != null && _dsPayment.Tables.Count > 15 && _dsPayment.Tables[15].Rows.Count > 0)
            {
                if (!DateTime.TryParse(_dsPayment.Tables[15].Rows[0]["ModifiedDate"].ToString(), out _PremiumDate))
                {
                    _PremiumDate = dateTimeNow;
                }
                if (!Int64.TryParse(_dsPayment.Tables[15].Rows[0]["CXBrokerProviderId"].ToString(), out Provider))
                {
                    Provider = 0;
                }
                if (!Int32.TryParse(_dsPayment.Tables[15].Rows[0]["ProviderCoverTypeId"].ToString(), out CoverType))
                {
                    CoverType = 10;
                }
                if (_dsPayment.Tables[15].Rows[0]["PaymentOption"] != DBNull.Value)
                {
                    PaymentOption = _dsPayment.Tables[15].Rows[0]["PaymentOption"].ToString();
                }
                
                if (Provider == 29 || PaymentOption == "FP")
                {
                    ts = (_CurrentDate.Date - _PremiumDate.Date);
                    days = ts.Days;

                    if (noofrecords == 0)
                    {
                        if (days > 7)
                        {
                            lblPreAmtTitle.ForeColor = System.Drawing.Color.Black;
                            lblPreAmtWODTitle.ForeColor = System.Drawing.Color.Green;

                            lblPreAmtTitle.Font.Bold = false;
                            lblPreAmtWODTitle.Font.Bold = true;

                            txtIsWD.Text = "1";
                            //txtIsWD.Text = "0";
                        }
                        else
                        {                            
                            lblPreAmtTitle.ForeColor = System.Drawing.Color.Green;
                            lblPreAmtWODTitle.ForeColor = System.Drawing.Color.Black;

                            lblPreAmtTitle.Font.Bold = true;
                            lblPreAmtWODTitle.Font.Bold = false;

                            txtIsWD.Text = "1";
                        }

                    }
                    else
                    {
                        if (_dsPayment.Tables[15].Rows[0]["FInfo1"] != DBNull.Value)
                        {
                            if (_dsPayment.Tables[15].Rows[0]["FInfo1"].ToString() == _dsPayment.Tables[15].Rows[0]["FinalAnnualPremium"].ToString())
                            {
                                lblPreAmtTitle.ForeColor = System.Drawing.Color.Black;
                                lblPreAmtWODTitle.ForeColor = System.Drawing.Color.Green;

                                lblPreAmtTitle.Font.Bold = false;
                                lblPreAmtWODTitle.Font.Bold = true;

                                txtIsWD.Text = "0";
                            }
                            else
                            {
                                lblPreAmtTitle.ForeColor = System.Drawing.Color.Green;
                                lblPreAmtWODTitle.ForeColor = System.Drawing.Color.Black;

                                lblPreAmtTitle.Font.Bold = true;
                                lblPreAmtWODTitle.Font.Bold = false;

                                txtIsWD.Text = "1";
                            }
                        }
                        else
                        {
                            lblPreAmtTitle.ForeColor = System.Drawing.Color.Green;
                            lblPreAmtWODTitle.ForeColor = System.Drawing.Color.Black;

                            lblPreAmtTitle.Font.Bold = true;
                            lblPreAmtWODTitle.Font.Bold = false;

                            txtIsWD.Text = "1";
                        }
                    }
                }
                else
                {
                    lblPreAmtTitle.ForeColor = System.Drawing.Color.Black;
                    lblPreAmtWODTitle.ForeColor = System.Drawing.Color.Green;

                    lblPreAmtTitle.Font.Bold = false;
                    lblPreAmtWODTitle.Font.Bold = true;

                    txtIsWD.Text = "0";
                }

                txtDays.Text = days.ToString();
            }

        }
        catch (Exception ex)
        {
        }
    }

    //public void LoadLableColorOld()
    //{
    //    try
    //    {
    //        DataSet _dsPayment = new DataSet();
    //        DateTime _PremiumDate = dateTimeNow;
    //        DateTime _PremiumWDDate = dateTimeNow;
    //        DateTime _CurrentDate = dateTimeNow;
    //        TimeSpan ts;
    //        Int32 days = 0;
    //        Int32 noofrecords = 0;
    //        txtIsWD.Text = "1";

    //        _dsPayment = GetApprovedPayments();// GetBrokerPremium();
    //        if (_dsPayment != null && _dsPayment.Tables.Count > 14 && _dsPayment.Tables[14].Rows.Count > 0)
    //        {
    //            txtNoOfRecords.Text = _dsPayment.Tables[14].Rows.Count.ToString();
    //            if (!Int32.TryParse(txtNoOfRecords.Text, out noofrecords))
    //            {
    //                noofrecords = 0;
    //            }
    //        }

    //        if (_dsPayment != null && _dsPayment.Tables.Count > 15 && _dsPayment.Tables[15].Rows.Count > 0)
    //        {
    //            if (!DateTime.TryParse(_dsPayment.Tables[15].Rows[0]["ModifiedDate"].ToString(), out _PremiumDate))
    //            {
    //                _PremiumDate = dateTimeNow;
    //            }

    //            ts = (_CurrentDate.Date - _PremiumDate.Date);
    //            days = ts.Days;

    //            if (noofrecords == 0)
    //            {
    //                if (days > 7)
    //                {
    //                    lblPreAmtTitle.ForeColor = System.Drawing.Color.Black;
    //                    lblPreAmtWODTitle.ForeColor = System.Drawing.Color.Green;

    //                    lblPreAmtTitle.Font.Bold = false;
    //                    lblPreAmtWODTitle.Font.Bold = true;

    //                    txtIsWD.Text = "0";
    //                }
    //                else
    //                {
    //                    lblPreAmtTitle.ForeColor = System.Drawing.Color.Green;
    //                    lblPreAmtWODTitle.ForeColor = System.Drawing.Color.Black;

    //                    lblPreAmtTitle.Font.Bold = true;
    //                    lblPreAmtWODTitle.Font.Bold = false;

    //                    txtIsWD.Text = "1";
    //                }
    //            }
    //            else
    //            {
    //                if (_dsPayment.Tables[15].Rows[0]["FInfo1"] != DBNull.Value)
    //                {
    //                    if (_dsPayment.Tables[15].Rows[0]["FInfo1"].ToString() == _dsPayment.Tables[15].Rows[0]["FinalAnnualPremium"].ToString())
    //                    {
    //                        lblPreAmtTitle.ForeColor = System.Drawing.Color.Black;
    //                        lblPreAmtWODTitle.ForeColor = System.Drawing.Color.Green;

    //                        lblPreAmtTitle.Font.Bold = false;
    //                        lblPreAmtWODTitle.Font.Bold = true;

    //                        txtIsWD.Text = "0";
    //                    }
    //                    else
    //                    {
    //                        lblPreAmtTitle.ForeColor = System.Drawing.Color.Green;
    //                        lblPreAmtWODTitle.ForeColor = System.Drawing.Color.Black;

    //                        lblPreAmtTitle.Font.Bold = true;
    //                        lblPreAmtWODTitle.Font.Bold = false;

    //                        txtIsWD.Text = "1";
    //                    }
    //                }
    //                else
    //                {
    //                    lblPreAmtTitle.ForeColor = System.Drawing.Color.Green;
    //                    lblPreAmtWODTitle.ForeColor = System.Drawing.Color.Black;

    //                    lblPreAmtTitle.Font.Bold = true;
    //                    lblPreAmtWODTitle.Font.Bold = false;

    //                    txtIsWD.Text = "1";
    //                }
    //            }
    //            txtDays.Text = days.ToString();
    //        }
    //    }
    //    catch (Exception ex)
    //    {
    //    }
    //}

    public void EnableDisable()
    {
        bool Enable = true;
        if (txtPaymentId.Text != string.Empty && Convert.ToInt64(txtPaymentId.Text.Trim()) > 0)
        {
            Enable = false;
        }
        ddlPaymentType.Enabled = Enable;
        ddlPaymentOption.Enabled = Enable;
        ddlNoOfInstallments.Enabled = Enable;
        ddlIssuingBank.Enabled = Enable;
        ddlBank.Enabled = Enable;
        txtIssuingBank.Enabled = Enable;
        ddlCardType.Enabled = Enable;
        //txtCardHolder.Enabled = Enable;
        //txtCardNo1.Enabled = Enable;
        //txtCardNo2.Enabled = Enable;
        //txtCardNo3.Enabled = Enable;
        //txtCardNo4.Enabled = Enable;
        //txtCardExpiryMonth.Enabled = Enable;
        //txtCardExpiryYear.Enabled = Enable;
        //txtCVV.Enabled = Enable;
    }

    public bool SendApproveMailToAdmin(Int16 TransactionType, string CustomerName, string Amount, string BrokerEmail, Int16 Status)
    {
        bool _result = true;
        string mailBody = "";
        string _emailTitle = "";
        string _toemail = "";
        string _ccemail = "";
        string _bccemail = "";
        _emailTitle = "[" + lblUpRefNo.Text + "] " + Resources.CarInsurance.Payment + "  [" + txtPlateNumber.Text + "]";
        mailBody = Resources.General.CustomerName + " : " + CustomerName + "<br/><br/>";
        mailBody += Resources.CarInsurance.Amount + " : " + Amount + "<br/><br/>";
        if (TransactionType == 1)
        {
            mailBody += Resources.General.TransactionType + " : " + Resources.CarInsurance.Payment + "<br/><br/>";
        }
        else if (TransactionType == 2)
        {
            mailBody += Resources.General.TransactionType + " : " + Resources.CarInsurance.Refund + "<br/><br/>";
        }
        if (Status == 1)
        {
            mailBody += Resources.General.Status + " : <b style='color:green;'>" + Resources.CarInsurance.Approve + "</b><br/><br/>";
        }
        else if (Status == 0)
        {
            mailBody += Resources.General.Status + " : <b style='color:red;'>" + Resources.General.Decline + "</b><br/><br/>";
        }

        mailBody += Resources.General.DateTime + " : " + dateTimeNow.ToString("dd-MMM-yyyy hh:mm:ss tt") + "<br/><br/>";
        _toemail = CE.Configuration.MyConfigurationManager.GetAppSettingValue("ADMIN");
        _toemail += BrokerEmail;
        _bccemail = "";

        if (Session[General.UserRole].ToString() == "100")
        {
            _ccemail += Session[General.SMTPReplyTo].ToString();
        }

        

        _result = MyMailManager.SendGGMail(ConfigurationManager.AppSettings["GGFormsSMTPAccount"].ToString(), ConfigurationManager.AppSettings["GGFormsSMTPAuthCode"].ToString(), _toemail, _ccemail, _bccemail, _emailTitle, mailBody, Session[General.SMTPReplyTo].ToString());

        return _result;
    }

    private string GetSMTPAccount(string smtpKey)
    {
        string _retValue = string.Empty;

        if (smtpKey == "admin")
        {
            _retValue = ConfigurationManager.AppSettings["ADMIN"].ToString();
        }
        else if (smtpKey == "cashier")
        {
            _retValue = ConfigurationManager.AppSettings["CASH"].ToString();
        }
        else if (smtpKey == "broker1")
        {
            _retValue = ConfigurationManager.AppSettings["Broker1ReplyTo"].ToString();
        }
        else if (smtpKey == "broker2")
        {
            _retValue = ConfigurationManager.AppSettings["Broker2ReplyTo"].ToString();
        }
        else if (smtpKey == "broker3")
        {
            _retValue = ConfigurationManager.AppSettings["Broker3ReplyTo"].ToString();
        }
        else if (smtpKey == "broker4")
        {
            _retValue = ConfigurationManager.AppSettings["Broker4ReplyTo"].ToString();
        }
        else if (smtpKey == "broker5")
        {
            _retValue = ConfigurationManager.AppSettings["Broker5ReplyTo"].ToString();
        }
        else if (smtpKey == "broker6")
        {
            _retValue = ConfigurationManager.AppSettings["Broker6ReplyTo"].ToString();
        }
        else if (smtpKey == "broker7")
        {
            _retValue = ConfigurationManager.AppSettings["Broker7ReplyTo"].ToString();
        }

        return _retValue;
    }

    private string GetProviderPremium(float NetPremium, float Discount, string CTPL, string CTPLAmount)
    {
        string _retValue = string.Empty;
        try
        {
            if (CTPL.ToString() == string.Empty)
            {
                CTPL = "NO";
            }
            if (CTPLAmount.ToString() == string.Empty)
            {
                CTPLAmount = "0";
            }
            decimal _netPremium = Convert.ToDecimal(NetPremium.ToString());

            decimal _tax = 0;
            _tax = Convert.ToDecimal(_netPremium * (0.4M / 100.0M));
            _tax = Convert.ToDecimal(_tax.ToString("#.00"));

            decimal _vat = 0;
            decimal _vatamt1 = 0;
            decimal _vatamt2 = 0;
            _vatamt1 = Convert.ToDecimal((_netPremium + _tax).ToString("#.00"));
            _vatamt2 = Convert.ToDecimal(7.0M / 100.0M);
            _vat = Convert.ToDecimal(_vatamt1 * _vatamt2);
            
            _vat = Convert.ToDecimal(_vat.ToString("#.00"));


            decimal _annualPremium = 0;

            if (Discount > 0)
            {
                decimal _discountAmount = Convert.ToDecimal((_netPremium * Convert.ToDecimal(Convert.ToDecimal(Discount) / 100.0M)));
                _annualPremium = _netPremium - _discountAmount;
                _annualPremium = _annualPremium + _vat + Math.Ceiling(_tax); ;
            }
            else
            {
                _annualPremium = _netPremium + _vat + Math.Ceiling(_tax);
            }

            if (CTPL == "YES")
            {
                _annualPremium = _annualPremium + Math.Ceiling(Convert.ToDecimal(CTPLAmount.ToString()));
            }
            _retValue = _annualPremium.ToString("#.00");
        }
        catch (Exception Ex)
        {
            Ex = null;
        }

        return _retValue;
    }

    private string GetProviderPremium(float GrossPremium, string CTPL, string CTPLAmount)
    {
        string _retValue = string.Empty;
        try
        {
            if (CTPL.ToString() == string.Empty)
            {
                CTPL = "NO";
            }
            if (CTPLAmount.ToString() == string.Empty)
            {
                CTPLAmount = "0";
            }
            decimal _grossPremium = Convert.ToDecimal(GrossPremium.ToString());
            if (CTPL == "YES")
            {
                _grossPremium = _grossPremium + Convert.ToDecimal(CTPLAmount.ToString());
            }
            _retValue = _grossPremium.ToString("#.00");
        }
        catch (Exception Ex)
        {
            Ex = null;
        }

        return _retValue;
    }

    private string GetBankName(string BankCode)
    {
        string _BankName = string.Empty;

        if (BankCode == "CHINS")
        {
            _BankName = Resources.CarInsurance.CashInstallment;
        }
        else if (BankCode == "BKK")
        {
            _BankName = Resources.CarInsurance.BankBKK;
        }
        else if (BankCode == "CITI")
        {
            _BankName = Resources.CarInsurance.BankCITI;
        }
        else if (BankCode == "KBANK")
        {
            _BankName = Resources.CarInsurance.BankK;
        }
        else if (BankCode == "KTC")
        {
            _BankName = Resources.CarInsurance.BankKTC;
        }
        else if (BankCode == "AYA")
        {
            _BankName = Resources.CarInsurance.BankAYA;
        }
        else if (BankCode == "CTRL")
        {
            _BankName = Resources.CarInsurance.CentralCard;
        }
        else if (BankCode == "RBSN")
        {
            _BankName = Resources.CarInsurance.RobinsonCard;
        }
        else if (BankCode == "HPRO")
        {
            _BankName = Resources.CarInsurance.HomeproCard;
        }
        else
        {
            _BankName = Resources.CarInsurance.Select;
        }

        return _BankName;
    }

    private void PaymentGridLoad()
    {
        DataSet _dsPayment = new DataSet();
        _dsPayment = GetBrokerPremium();
        if (_dsPayment != null && _dsPayment.Tables.Count > 1 && _dsPayment.Tables[1].Rows.Count > 0)
        {
            lblPaymentMode.Text = "";
            if (_dsPayment.Tables[0].Rows[0]["PaymentMode"] != DBNull.Value)
            {
                if (_dsPayment.Tables[0].Rows[0]["PaymentMode"].ToString() == "CR")
                    lblPaymentMode.Text = "Credit Card";
                else if (_dsPayment.Tables[0].Rows[0]["PaymentMode"].ToString() == "TR")
                    lblPaymentMode.Text = "โอนเงิน";
            }

            txtAgentComments.Text = "";
            if (_dsPayment != null && _dsPayment.Tables.Count > 0 && _dsPayment.Tables[0].Rows.Count > 0)
            {
                if (_dsPayment.Tables[0].Rows[0]["Info8"] != DBNull.Value && _dsPayment.Tables[0].Rows[0]["Info8"].ToString() != string.Empty)
                {
                    txtAgentComments.Text = _dsPayment.Tables[0].Rows[0]["Info8"].ToString();
                }
            }
            txtBalanceAmount.Text = "0";
            lblPayBalance.Text = "0";
            txtTotalCollectedAmount.Text = "0";
            txtTotalRefundAmount.Text = "0";
            grvPayment.DataSource = _dsPayment.Tables[1];
            grvPayment.DataBind();
            txtPaymentId.Text = "0";
            EnableDisable();
            if (grvPayment.Rows.Count > 0)
            {
                btnPaymentApproval.Enabled = true;
                chkRefund.Enabled = true;
                DataSet _dsPaymentAmount = new DataSet();
                _dsPaymentAmount = GetPaymentAmounts();
                if (_dsPaymentAmount != null && _dsPaymentAmount.Tables.Count > 0 && _dsPaymentAmount.Tables[0].Rows.Count > 0)
                {
                    
                    txtTotalCollectedAmount.Text = _dsPaymentAmount.Tables[0].Rows[0]["CollectedAmount"].ToString();
                    txtTotalRefundAmount.Text = _dsPaymentAmount.Tables[0].Rows[0]["RefundAmount"].ToString();
                }
                divPayList.Visible = true;
                
            }
            else
            {
                divPayList.Visible = false;
                grvPayment.DataSource = null;
                grvPayment.DataBind();
            }
        }
    }

    private void ShowTescoAmount()
    {
        string strCommence = "";
        string minPremium = "0";
        decimal _Premium = 0;
        
        DataTable dt = new DataTable();
        DataSet _dsSelect = new DataSet();
        DataTable _dtSelect = new DataTable();
        DateTime _CoverCommDate = dateTimeNow;
        DateTime _CurrentDate = dateTimeNow;
        TimeSpan ts;
        Int32 days = 0;
        Int32 RecordCount = 0;

        //Yui@30Jan2015 : Renew get same tesco discount as online
        //if (ddlApplicationType.Text == "REN" || ddlApplicationType.Text == "RNO")
        //{
        //    lblTescoSelection.Text = "N/A";
        //    txtTescoSelectedId.Text = "0";
        //    txtTescoAmount.Text = "0.00";
        //    txtHideTescoWD.Text = "0";
        //    txtHideTescoWOD.Text = "0";
        //    chkTescoVoucher.Checked = false;
        //    chkTescoCash.Checked = false;
        //}
        //else
        //{
        MyDatabase _db = new MyDatabase("GG_CRMDBConnectionString");
        SortedList _sPara = new SortedList();
        string _spName = "sprocCXCRMTescoAmountSelectedByCarId";
        _sPara.Add("@CECarId", Convert.ToInt64(txtCarId.Text.Trim()));
        _sPara.Add("@ProviderId", Convert.ToInt64(txtProviderId.Text));
        _dsSelect = _db.GetDataSet(_spName, _sPara);
        if (_dsSelect != null && _dsSelect.Tables.Count > 0)
        {
            txtHideTescoWD.Text = "0";
            txtHideTescoWOD.Text = "0";
            RecordCount = Convert.ToInt32(_dsSelect.Tables[0].Rows[0]["RecordCount"].ToString());
            if (RecordCount > 0)
            {
                if (_dsSelect.Tables.Count > 1)
                {
                    decimal _tecoamont = 0;
                    if (_dsSelect.Tables[1].Rows[0]["TescoSelect"] != DBNull.Value && _dsSelect.Tables[1].Rows[0]["TescoSelect"].ToString() == "1")
                    {
                        lblTescoSelection.Text = "Voucher";
                        txtTescoSelectedId.Text = "1";
                        chkTescoVoucher.Checked = true;
                    }
                    else if (_dsSelect.Tables[1].Rows[0]["TescoSelect"] != DBNull.Value && _dsSelect.Tables[1].Rows[0]["TescoSelect"].ToString() == "2")
                    {
                        lblTescoSelection.Text = "Cash";
                        txtTescoSelectedId.Text = "2";
                        chkTescoCash.Checked = true;
                    }
                    else
                    {
                        lblTescoSelection.Text = "N/A";
                        txtTescoSelectedId.Text = "0";
                        chkTescoVoucher.Checked = false;
                        chkTescoCash.Checked = false;
                    }
                    if (_dsSelect.Tables.Count > 3 && _dsSelect.Tables[3].Rows.Count > 0)
                    {
                        if (_dsSelect.Tables[1].Rows[0]["TescoAmount"] != DBNull.Value && (decimal.TryParse(_dsSelect.Tables[1].Rows[0]["TescoAmount"].ToString(), out _tecoamont)))
                        {
                            txtTescoAmount.Text = _tecoamont.ToString("#0.00");
                            txtHideTescoWD.Text = _tecoamont.ToString("#0.00");
                            txtHideTescoWOD.Text = _tecoamont.ToString("#0.00");
                        }
                        else
                        {
                            txtTescoAmount.Text = "0.00";
                            txtHideTescoWD.Text = "0";
                            txtHideTescoWOD.Text = "0";
                        }
                    }
                    else
                    {
                        if (_dsSelect.Tables.Count > 1)
                        {
                            if (_dsSelect.Tables[1].Rows[0]["FinalAnnualPremium"] != DBNull.Value && _dsSelect.Tables[1].Rows[0]["FinalAnnualPremium"].ToString() != string.Empty)
                            {
                                minPremium = _dsSelect.Tables[1].Rows[0]["FinalAnnualPremium"].ToString();
                            }

                                                       
                        }
                        if (_dsSelect.Tables.Count > 2)
                        {
                            if (_dsSelect.Tables[2].Rows[0]["CoverageCommenceDate"] != DBNull.Value && _dsSelect.Tables[2].Rows[0]["CoverageCommenceDate"].ToString() != string.Empty)
                            {
                                strCommence = _dsSelect.Tables[2].Rows[0]["CoverageCommenceDate"].ToString();
                            }
                        }

                        if (!decimal.TryParse(minPremium, out _Premium))
                        {
                            _Premium = 0;
                        }
                       
                        if (!DateTime.TryParse(strCommence, out _CoverCommDate))
                        {
                            _CoverCommDate = new DateTime();
                        }
                        ts = (_CoverCommDate.Date - _CurrentDate.Date);
                        days = ts.Days;
                        txtTescoAmount.Text = "0";

                        #region With Discount
                        txtHideTescoWD.Text = "0";
                        if (_Premium > 0 && _Premium <= 12000)
                        {
                            if (days > 60)
                            {
                                txtTescoAmount.Text = "200";
                                txtHideTescoWD.Text = "200";
                            }
                        }
                        else if (_Premium > 12000 && _Premium <= 15000)
                        {
                            if (days >= 15 && days <= 30)
                            {
                                txtTescoAmount.Text = "200";
                                txtHideTescoWD.Text = "200";
                            }
                            else if (days > 30 && days <= 60)
                            {
                                txtTescoAmount.Text = "300";
                                txtHideTescoWD.Text = "300";
                            }
                            else if (days > 60)
                            {
                                txtTescoAmount.Text = "400";
                                txtHideTescoWD.Text = "400";
                            }
                        }
                        else if (_Premium > 15000 && _Premium <= 20000)
                        {
                            if (days >= 15 && days <= 30)
                            {
                                txtTescoAmount.Text = "300";
                                txtHideTescoWD.Text = "300";
                            }
                            else if (days > 30 && days <= 60)
                            {
                                txtTescoAmount.Text = "400";
                                txtHideTescoWD.Text = "400";
                            }
                            else if (days > 60)
                            {
                                txtTescoAmount.Text = "600";
                                txtHideTescoWD.Text = "600";
                            }
                        }
                        else if (_Premium > 20000 && _Premium <= 30000)
                        {
                            if (days >= 15 && days <= 30)
                            {
                                txtTescoAmount.Text = "400";
                                txtHideTescoWD.Text = "400";
                            }
                            else if (days > 30 && days <= 60)
                            {
                                txtTescoAmount.Text = "500";
                                txtHideTescoWD.Text = "500";
                            }
                            else if (days > 60)
                            {
                                txtTescoAmount.Text = "700";
                                txtHideTescoWD.Text = "700";
                            }
                        }
                        else if (_Premium > 30000 && _Premium <= 40000)
                        {
                            if (days >= 15 && days <= 30)
                            {
                                txtTescoAmount.Text = "500";
                                txtHideTescoWD.Text = "500";
                            }
                            else if (days > 30 && days <= 60)
                            {
                                txtTescoAmount.Text = "600";
                                txtHideTescoWD.Text = "600";
                            }
                            else if (days > 60)
                            {
                                txtTescoAmount.Text = "800";
                                txtHideTescoWD.Text = "800";
                            }
                        }
                        else if (_Premium > 40000)
                        {
                            if (days >= 15 && days <= 30)
                            {
                                txtTescoAmount.Text = "600";
                                txtHideTescoWD.Text = "600";
                            }
                            else if (days > 30 && days <= 60)
                            {
                                txtTescoAmount.Text = "700";
                                txtHideTescoWD.Text = "700";
                            }
                            else if (days > 60)
                            {
                                txtTescoAmount.Text = "1000";
                                txtHideTescoWD.Text = "1000";
                            }
                        }
                        txtHideTescoWOD.Text = txtHideTescoWD.Text.Trim();
                        #endregion

                        #region Without Discount
                        /*txtHideTescoWOD.Text = "0";
                    if (_Premiumwod > 0 && _Premiumwod <= 12000)
                    {
                        if (days > 60)
                        {
                            txtHideTescoWOD.Text = "200";
                        }
                    }
                    else if (_Premiumwod > 12000 && _Premiumwod <= 15000)
                    {
                        if (days >= 15 && days <= 30)
                        {
                            txtHideTescoWOD.Text = "200";
                        }
                        else if (days > 30 && days <= 60)
                        {
                            txtHideTescoWOD.Text = "300";
                        }
                        else if (days > 60)
                        {
                            txtHideTescoWOD.Text = "400";
                        }
                    }
                    else if (_Premiumwod > 15000 && _Premiumwod <= 20000)
                    {
                        if (days >= 15 && days <= 30)
                        {
                            txtHideTescoWOD.Text = "300";
                        }
                        else if (days > 30 && days <= 60)
                        {
                            txtHideTescoWOD.Text = "400";
                        }
                        else if (days > 60)
                        {
                            txtHideTescoWOD.Text = "600";
                        }
                    }
                    else if (_Premiumwod > 20000 && _Premiumwod <= 30000)
                    {
                        if (days >= 15 && days <= 30)
                        {
                            txtHideTescoWOD.Text = "400";
                        }
                        else if (days > 30 && days <= 60)
                        {
                            txtHideTescoWOD.Text = "500";
                        }
                        else if (days > 60)
                        {
                            txtHideTescoWOD.Text = "700";
                        }
                    }
                    else if (_Premiumwod > 30000 && _Premiumwod <= 40000)
                    {
                        if (days >= 15 && days <= 30)
                        {
                            txtHideTescoWOD.Text = "500";
                        }
                        else if (days > 30 && days <= 60)
                        {
                            txtHideTescoWOD.Text = "600";
                        }
                        else if (days > 60)
                        {
                            txtHideTescoWOD.Text = "800";
                        }
                    }
                    else if (_Premiumwod > 40000)
                    {
                        if (days >= 15 && days <= 30)
                        {
                            txtHideTescoWOD.Text = "600";
                        }
                        else if (days > 30 && days <= 60)
                        {
                            txtHideTescoWOD.Text = "700";
                        }
                        else if (days > 60)
                        {
                            txtHideTescoWOD.Text = "1,000";
                        }
                    }*/
                        #endregion

                    }
                }
            }
            else
            {
                if (_dsSelect.Tables.Count > 1)
                {
                    if (_dsSelect.Tables[1].Rows[0]["TescoSelect"] != DBNull.Value && _dsSelect.Tables[1].Rows[0]["TescoSelect"].ToString() == "1")
                    {
                        lblTescoSelection.Text = "Voucher";
                        txtTescoSelectedId.Text = "1";
                        chkTescoVoucher.Checked = true;
                    }
                    else if (_dsSelect.Tables[1].Rows[0]["TescoSelect"] != DBNull.Value && _dsSelect.Tables[1].Rows[0]["TescoSelect"].ToString() == "2")
                    {
                        lblTescoSelection.Text = "Cash";
                        txtTescoSelectedId.Text = "2";
                        chkTescoCash.Checked = true;
                    }
                    else
                    {
                        lblTescoSelection.Text = "N/A";
                        txtTescoSelectedId.Text = "0";
                        chkTescoVoucher.Checked = false;
                        chkTescoCash.Checked = false;
                    }

                    if (_dsSelect.Tables[1].Rows[0]["FinalAnnualPremium"] != DBNull.Value && _dsSelect.Tables[1].Rows[0]["FinalAnnualPremium"].ToString() != string.Empty)
                    {
                        minPremium = _dsSelect.Tables[1].Rows[0]["FinalAnnualPremium"].ToString();
                    }
                }
                if (_dsSelect.Tables.Count > 1)
                {
                    if (_dsSelect.Tables[1].Rows[0]["FinalAnnualPremium"] != DBNull.Value && _dsSelect.Tables[1].Rows[0]["FinalAnnualPremium"].ToString() != string.Empty)
                    {
                        minPremium = _dsSelect.Tables[1].Rows[0]["FinalAnnualPremium"].ToString();
                    }
                }
                if (_dsSelect.Tables.Count > 2)
                {
                    if (_dsSelect.Tables[2].Rows[0]["CoverageCommenceDate"] != DBNull.Value && _dsSelect.Tables[2].Rows[0]["CoverageCommenceDate"].ToString() != string.Empty)
                    {
                        strCommence = _dsSelect.Tables[2].Rows[0]["CoverageCommenceDate"].ToString();
                    }
                }

                if (!decimal.TryParse(minPremium, out _Premium))
                {
                    _Premium = 0;
                }
                
                if (!DateTime.TryParse(strCommence, out _CoverCommDate))
                {
                    _CoverCommDate = new DateTime();
                }
                ts = (_CoverCommDate.Date - _CurrentDate.Date);
                days = ts.Days;
                txtTescoAmount.Text = "0";

                #region With Discount
                txtHideTescoWD.Text = "0";
                if (_Premium > 0 && _Premium <= 12000)
                {
                    if (days > 60)
                    {
                        txtTescoAmount.Text = "200";
                        txtHideTescoWD.Text = "200";
                    }
                }
                else if (_Premium > 12000 && _Premium <= 15000)
                {
                    if (days >= 15 && days <= 30)
                    {
                        txtTescoAmount.Text = "200";
                        txtHideTescoWD.Text = "200";
                    }
                    else if (days > 30 && days <= 60)
                    {
                        txtTescoAmount.Text = "300";
                        txtHideTescoWD.Text = "300";
                    }
                    else if (days > 60)
                    {
                        txtTescoAmount.Text = "400";
                        txtHideTescoWD.Text = "400";
                    }
                }
                else if (_Premium > 15000 && _Premium <= 20000)
                {
                    if (days >= 15 && days <= 30)
                    {
                        txtTescoAmount.Text = "300";
                        txtHideTescoWD.Text = "300";
                    }
                    else if (days > 30 && days <= 60)
                    {
                        txtTescoAmount.Text = "400";
                        txtHideTescoWD.Text = "400";
                    }
                    else if (days > 60)
                    {
                        txtTescoAmount.Text = "600";
                        txtHideTescoWD.Text = "600";
                    }
                }
                else if (_Premium > 20000 && _Premium <= 30000)
                {
                    if (days >= 15 && days <= 30)
                    {
                        txtTescoAmount.Text = "400";
                        txtHideTescoWD.Text = "400";
                    }
                    else if (days > 30 && days <= 60)
                    {
                        txtTescoAmount.Text = "500";
                        txtHideTescoWD.Text = "500";
                    }
                    else if (days > 60)
                    {
                        txtTescoAmount.Text = "700";
                        txtHideTescoWD.Text = "700";
                    }
                }
                else if (_Premium > 30000 && _Premium <= 40000)
                {
                    if (days >= 15 && days <= 30)
                    {
                        txtTescoAmount.Text = "500";
                        txtHideTescoWD.Text = "500";
                    }
                    else if (days > 30 && days <= 60)
                    {
                        txtTescoAmount.Text = "600";
                        txtHideTescoWD.Text = "600";
                    }
                    else if (days > 60)
                    {
                        txtTescoAmount.Text = "800";
                        txtHideTescoWD.Text = "800";
                    }
                }
                else if (_Premium > 40000)
                {
                    if (days >= 15 && days <= 30)
                    {
                        txtTescoAmount.Text = "600";
                        txtHideTescoWD.Text = "600";
                    }
                    else if (days > 30 && days <= 60)
                    {
                        txtTescoAmount.Text = "700";
                        txtHideTescoWD.Text = "700";
                    }
                    else if (days > 60)
                    {
                        txtTescoAmount.Text = "1000";
                        txtHideTescoWD.Text = "1000";
                    }
                }
                txtHideTescoWOD.Text = txtHideTescoWD.Text.Trim();
                #endregion

                #region Without Discount
                /*txtHideTescoWOD.Text = "0";
            if (_Premiumwod > 0 && _Premiumwod <= 12000)
            {
                if (days > 60)
                {
                    txtHideTescoWOD.Text = "200";
                }
            }
            else if (_Premiumwod > 12000 && _Premiumwod <= 15000)
            {
                if (days >= 15 && days <= 30)
                {
                    txtHideTescoWOD.Text = "200";
                }
                else if (days > 30 && days <= 60)
                {
                    txtHideTescoWOD.Text = "300";
                }
                else if (days > 60)
                {
                    txtHideTescoWOD.Text = "400";
                }
            }
            else if (_Premiumwod > 15000 && _Premiumwod <= 20000)
            {
                if (days >= 15 && days <= 30)
                {
                    txtHideTescoWOD.Text = "300";
                }
                else if (days > 30 && days <= 60)
                {
                    txtHideTescoWOD.Text = "400";
                }
                else if (days > 60)
                {
                    txtHideTescoWOD.Text = "600";
                }
            }
            else if (_Premiumwod > 20000 && _Premiumwod <= 30000)
            {
                if (days >= 15 && days <= 30)
                {
                    txtHideTescoWOD.Text = "400";
                }
                else if (days > 30 && days <= 60)
                {
                    txtHideTescoWOD.Text = "500";
                }
                else if (days > 60)
                {
                    txtHideTescoWOD.Text = "700";
                }
            }
            else if (_Premiumwod > 30000 && _Premiumwod <= 40000)
            {
                if (days >= 15 && days <= 30)
                {
                    txtHideTescoWOD.Text = "500";
                }
                else if (days > 30 && days <= 60)
                {
                    txtHideTescoWOD.Text = "600";
                }
                else if (days > 60)
                {
                    txtHideTescoWOD.Text = "800";
                }
            }
            else if (_Premiumwod > 40000)
            {
                if (days >= 15 && days <= 30)
                {
                    txtHideTescoWOD.Text = "600";
                }
                else if (days > 30 && days <= 60)
                {
                    txtHideTescoWOD.Text = "700";
                }
                else if (days > 60)
                {
                    txtHideTescoWOD.Text = "1,000";
                }
            }*/
                #endregion
            }

            decimal _tescowd = 0;
            decimal _tescowod = 0;
            decimal _premiumwd = 0;
            decimal _premiumwod = 0;
            decimal _showpremiumwd = 0;
            decimal _showpremiumwod = 0;
            if (!decimal.TryParse(txtHideTescoWD.Text, out _tescowd))
            {
                _tescowd = 0;
            }
            if (!decimal.TryParse(txtHideTescoWOD.Text, out _tescowod))
            {
                _tescowod = 0;
            }
            if (!decimal.TryParse(txtWDPremium.Text, out _premiumwd))
            {
                _premiumwd = 0;
            }
            if (!decimal.TryParse(txtWODPremium.Text, out _premiumwod))
            {
                _premiumwod = 0;
            }

            _showpremiumwd = (_premiumwd - _tescowd);
            _showpremiumwod = (_premiumwod - _tescowod);

            txtAFTPremiumWD.Text = _showpremiumwd.ToString("#0.00");
            txtAFTPremiumWOD.Text = _showpremiumwod.ToString("#0.00");

            if (txtIsWD.Text != string.Empty && txtIsWD.Text == "0")
            {
                txtTescoAmount.Text = txtHideTescoWOD.Text;
            }
            else
            {
                txtTescoAmount.Text = txtHideTescoWD.Text;
            }
        }
        //}

        txtTescoAmountSelection.Text = txtTescoAmount.Text;
        if (txtIsWD.Text != string.Empty && txtIsWD.Text == "0")
        {
            if (chkTescoCash.Checked)
            {
                txtFinalPrice.Text = txtAFTPremiumWOD.Text.Trim();
                lblUpPremium.Text = txtAFTPremiumWOD.Text.Trim();
            }
            else
            {
                txtFinalPrice.Text = txtWODPremium.Text.Trim();
                lblUpPremium.Text = txtWODPremium.Text.Trim();
            }
            lblPayPremium.Text = txtWODPremium.Text.Trim();
            lblPayPremiumAfterTescoCash.Text = txtAFTPremiumWOD.Text.Trim();
        }
        else
        {
            if (chkTescoCash.Checked)
            {
                txtFinalPrice.Text = txtAFTPremiumWD.Text.Trim();
                lblUpPremium.Text = txtAFTPremiumWD.Text.Trim();
            }
            else
            {
                txtFinalPrice.Text = txtWDPremium.Text.Trim();
                lblUpPremium.Text = txtWDPremium.Text.Trim();
            }
            lblPayPremium.Text = txtWDPremium.Text.Trim();
            lblPayPremiumAfterTescoCash.Text = txtAFTPremiumWD.Text.Trim();
        }

        #region Get Final Approve Premium
        MyDatabase _myDB = new MyDatabase();
        txtCashierApproved.Text = "0";
        string _strCashierApprovedPremium = "0";
        decimal _dCashierApprovedPremium = 0;
        string strSelectSql = "SELECT Approved, ApprovedPremium FROM tblCXBrokerPremium WHERE Info1 = '" + lblUpRefNo.Text.Trim() + "' AND SelectedStatus = 1 AND CECarId = " + txtCarId.Text.Trim();
        DataTable _SelectItemResult = _myDB.GetDataTable(strSelectSql);
        if (_SelectItemResult != null && _SelectItemResult.Rows.Count > 0)
        {
            if (_SelectItemResult.Rows[0]["Approved"] != DBNull.Value)
            {
                txtCashierApproved.Text = _SelectItemResult.Rows[0]["Approved"].ToString();
            }
            if (_SelectItemResult.Rows[0]["ApprovedPremium"] != DBNull.Value)
            {
                _strCashierApprovedPremium = _SelectItemResult.Rows[0]["ApprovedPremium"].ToString();
            }
        }
        if (txtCashierApproved.Text.Trim() != "0")
        {
            if (decimal.TryParse(_strCashierApprovedPremium, out _dCashierApprovedPremium))
            {
                txtFinalPrice.Text = _dCashierApprovedPremium.ToString("#0.00");
                lblUpPremium.Text = txtFinalPrice.Text.Trim();
            }
        }
        #endregion

        txtFinalApprovalPremium.Text = txtFinalPrice.Text.Trim();
        lblUpPremiumWD.Text = txtWDPremium.Text.Trim();
        lblUpPremiumWOD.Text = txtWODPremium.Text.Trim();

        decimal _collected = 0;
        decimal _refund = 0;
        decimal _final = 0;
        if (!decimal.TryParse(txtTotalCollectedAmount.Text.Trim(), out _collected))
        {
            _collected = 0;
        }
        if (!decimal.TryParse(txtTotalRefundAmount.Text.Trim(), out _refund))
        {
            _refund = 0;
        }
        if (!decimal.TryParse(txtFinalPrice.Text.Trim(), out _final))
        {
            _final = 0;
        }
       
        txtBalanceAmount.Text = (_final - _collected).ToString("#0.00");

        if (txtTescoAmount.Text != string.Empty && Convert.ToSingle(txtTescoAmount.Text.Trim()) <= 0)
        {
            divTescoCash.Visible = false;
            chkTescoCash.Checked = false;
            chkTescoVoucher.Checked = false;
            chkTescoCash.Enabled = false;
            chkTescoVoucher.Enabled = false;
        }
        else
        {
            divTescoCash.Visible = true;
            lblPayPremiumAfterTescoCashTitle.Text = Resources.General.Premium + " (หักส่วนลด Tesco)";
            chkTescoCash.Enabled = true;
            chkTescoVoucher.Enabled = true;
        }
        if (txtCashierApproved.Text != "0")
        {
            chkTescoVoucher.Enabled = false;
            chkTescoCash.Enabled = false;
        }
        decimal Tesco = 0;
        if (txtTescoSelectedId.Text == "0" && decimal.TryParse(txtTescoAmount.Text.Trim(), out Tesco))
        {
            if (Tesco <= 0 || (Tesco > 0 && Session[General.UserRole].ToString() == "300"))
            {
                tdTescoAmount.BgColor = "#D8D8D8";
                tdTescoAmountSelection.BgColor = "#D8D8D8";
                tdAFTPremiumWD.BgColor = "#D8D8D8";
                tdAFTPremiumWOD.BgColor = "#D8D8D8";

                txtTescoAmount.BackColor = System.Drawing.Color.LightGray;
                txtTescoAmountSelection.BackColor = System.Drawing.Color.LightGray;
                txtAFTPremiumWD.BackColor = System.Drawing.Color.LightGray;
                txtAFTPremiumWOD.BackColor = System.Drawing.Color.LightGray;

                txtTescoAmount.ForeColor = System.Drawing.Color.LightGray;
                txtTescoAmountSelection.ForeColor = System.Drawing.Color.LightGray;
                txtAFTPremiumWD.ForeColor = System.Drawing.Color.LightGray;
                txtAFTPremiumWOD.ForeColor = System.Drawing.Color.LightGray;

                txtTescoAmount.BorderColor = System.Drawing.Color.LightGray;
                txtTescoAmountSelection.BorderColor = System.Drawing.Color.LightGray;
                txtAFTPremiumWD.BorderColor = System.Drawing.Color.LightGray;
                txtAFTPremiumWOD.BorderColor = System.Drawing.Color.LightGray;
            }
        }
    }

    public void LoadPaymentCompletedStatus()
    {
        try
        {
            txtPaymentStatus.Text = "0";
            DateTime ApproveDate = dateTimeNow;
            MyDatabase _db = new MyDatabase();
            string strSql = @"SELECT TransactionId,CECarId,QuoteRefNo,ProviderCompanyId,Remarks,ModifiedDate FROM tblNonGGTransaction ";
            strSql += " WHERE TransactionTypeId = 100 AND [Status] = 1 AND CECarId =  " + txtCarId.Text;
            DataTable _dtTransaction = _db.GetDataTable(strSql);
            if (_dtTransaction != null && _dtTransaction.Rows.Count > 0)
            {
                txtTransactionId.Text = "-1";
                if (_dtTransaction.Rows[0]["TransactionId"] != DBNull.Value && _dtTransaction.Rows[0]["TransactionId"].ToString() != string.Empty)
                {
                    txtTransactionId.Text = _dtTransaction.Rows[0]["TransactionId"].ToString();
                    txtPaymentStatus.Text = "1";
                }
                if (_dtTransaction.Rows[0]["ModifiedDate"] != DBNull.Value && _dtTransaction.Rows[0]["ModifiedDate"].ToString() != string.Empty)
                {
                    if (!DateTime.TryParse(_dtTransaction.Rows[0]["ModifiedDate"].ToString(), out ApproveDate))
                    {
                        ApproveDate = dateTimeNow;
                    }
                    lblPaymentStatusMessage.Text = "Payment Completed Status Updated on " + ApproveDate.ToString("dd/MMM/yyyy hh:mm tt");
                }
            }
            if (txtPaymentStatus.Text.Trim() == "0")
            {
                lblPaymentStatusMessage.Text = "Payment Completed Status Not Updated Yet!";
            }
        }
        catch (Exception ex)
        {
        }
    }

    public bool CheckPaymentCompletedStatusDate()
    {
        try
        {
            bool ISValidtoDelete = true;
            DateTime TodayDate = dateTimeNow;
            DateTime ApproveDate = dateTimeNow;
            MyDatabase _db = new MyDatabase();
            string strSql = @"SELECT TransactionId,CECarId,QuoteRefNo,ProviderCompanyId,Remarks,ModifiedDate FROM tblNonGGTransaction ";
            strSql += " WHERE TransactionTypeId = 100 AND [Status] = 1 AND CECarId =  " + txtCarId.Text;
            DataTable _dtTransaction = _db.GetDataTable(strSql);
            if (_dtTransaction != null && _dtTransaction.Rows.Count > 0)
            {
                if (_dtTransaction.Rows[0]["ModifiedDate"] != DBNull.Value && _dtTransaction.Rows[0]["ModifiedDate"].ToString() != string.Empty)
                {
                    if (!DateTime.TryParse(_dtTransaction.Rows[0]["ModifiedDate"].ToString(), out ApproveDate))
                    {
                        ApproveDate = dateTimeNow;
                    }
                }
            }
            TimeSpan ts;
            Int32 days = 0;
            ts = (TodayDate.Date - ApproveDate.Date);
            days = ts.Days;
            if (days >= 15)
            {
                ISValidtoDelete = false;
            }
            return ISValidtoDelete;
        }
        catch (Exception ex)
        {
            return false;
        }
    }

    protected void chkTescoCash_CheckedChanged(object sender, EventArgs e)
    {
        if (txtCashierApproved.Text == "0")
        {
            if (chkTescoCash.Checked)
            {
                chkTescoVoucher.Checked = false;
                txtAmount.Text = lblPayPremiumAfterTescoCash.Text;
                txtFinalPrice.Text = lblPayPremiumAfterTescoCash.Text;
                txtAmount.ReadOnly = true;

                lblUpPremium.Text = txtFinalPrice.Text.Trim();
                lblUpPremiumWD.Text = txtAFTPremiumWD.Text.Trim();
                lblUpPremiumWOD.Text = txtAFTPremiumWOD.Text.Trim();
            }
            else if (chkTescoVoucher.Checked)
            {
                chkTescoCash.Checked = false;
                txtAmount.Text = lblPayPremium.Text;
                txtFinalPrice.Text = lblPayPremium.Text;
                txtAmount.ReadOnly = true;

                lblUpPremium.Text = txtFinalPrice.Text.Trim();
                lblUpPremiumWD.Text = txtWDPremium.Text.Trim();
                lblUpPremiumWOD.Text = txtWODPremium.Text.Trim();
            }
            else
            {
                txtAmount.Text = lblPayPremium.Text;
                txtFinalPrice.Text = lblPayPremium.Text;
                txtAmount.ReadOnly = false;

                lblUpPremium.Text = txtFinalPrice.Text.Trim();
                lblUpPremiumWD.Text = txtWDPremium.Text.Trim();
                lblUpPremiumWOD.Text = txtWODPremium.Text.Trim();
            }

            decimal _collected = 0;
            decimal _refund = 0;
            decimal _final = 0;
            if (!decimal.TryParse(txtTotalCollectedAmount.Text.Trim(), out _collected))
            {
                _collected = 0;
            }
            if (!decimal.TryParse(txtTotalRefundAmount.Text.Trim(), out _refund))
            {
                _refund = 0;
            }
            if (!decimal.TryParse(txtFinalPrice.Text.Trim(), out _final))
            {
                _final = 0;
            }
            
            txtBalanceAmount.Text = (_final - _collected).ToString("#0.00");
            txtFinalApprovalPremium.Text = txtFinalPrice.Text.Trim();
        }
    }

    protected void chkTescoVoucher_CheckedChanged(object sender, EventArgs e)
    {
        if (txtCashierApproved.Text == "0")
        {
            if (chkTescoVoucher.Checked)
            {
                chkTescoCash.Checked = false;
                txtAmount.Text = lblPayPremium.Text;
                txtFinalPrice.Text = lblPayPremium.Text;
                txtAmount.ReadOnly = true;

                lblUpPremium.Text = txtFinalPrice.Text.Trim();
                lblUpPremiumWD.Text = txtWDPremium.Text.Trim();
                lblUpPremiumWOD.Text = txtWODPremium.Text.Trim();
            }
            else if (chkTescoCash.Checked)
            {
                chkTescoVoucher.Checked = false;
                txtAmount.Text = lblPayPremiumAfterTescoCash.Text;
                txtFinalPrice.Text = lblPayPremiumAfterTescoCash.Text;
                txtAmount.ReadOnly = true;

                lblUpPremium.Text = txtFinalPrice.Text.Trim();
                lblUpPremiumWD.Text = txtAFTPremiumWD.Text.Trim();
                lblUpPremiumWOD.Text = txtAFTPremiumWOD.Text.Trim();
            }
            else
            {
                txtAmount.ReadOnly = false;

                lblUpPremium.Text = txtFinalPrice.Text.Trim();
                lblUpPremiumWD.Text = txtWDPremium.Text.Trim();
                lblUpPremiumWOD.Text = txtWODPremium.Text.Trim();
            }

            decimal _collected = 0;
            decimal _refund = 0;
            decimal _final = 0;
            if (!decimal.TryParse(txtTotalCollectedAmount.Text.Trim(), out _collected))
            {
                _collected = 0;
            }
            if (!decimal.TryParse(txtTotalRefundAmount.Text.Trim(), out _refund))
            {
                _refund = 0;
            }
            if (!decimal.TryParse(txtFinalPrice.Text.Trim(), out _final))
            {
                _final = 0;
            }
           
            txtBalanceAmount.Text = (_final - _collected).ToString("#0.00");
            txtFinalApprovalPremium.Text = txtFinalPrice.Text.Trim();
        }
    }

    #region Contact Quote Tab

    protected void btnGoToView_Click(object sender, EventArgs e)
    {
        try
        {
            if (txtUserId.Text != string.Empty && txtCarId.Text != string.Empty)
            {
                MyDatabase _db = new MyDatabase();
                DataTable _dt = new DataTable("tblNewCall");
                string _strReturnMessage = string.Empty;

                string _spName = "sprocCXCRMCheckNewRegularCall";
                SortedList _paraList = new SortedList();
                _paraList.Add("@CustomerID", txtUserId.Text);
                _paraList.Add("@CarID", txtCarId.Text);
                _paraList.Add("@AgentID", Session[General.UserId].ToString());
                
                _paraList.Add("@pCallType", (hidCallType.Value.Trim() != "" && hidCallType.Value.Trim() != "0" ? hidCallType.Value.Trim() : "100"));

                _dt = _db.GetDataTableBySP(_spName, _paraList);

                Int16 _callStatus = 0;
                Int16 _callType = 0;
                string tabs = "&tabid=" + hidLastTab.Value;
                if (_dt != null && _dt.Rows.Count > 0)
                {
                    if (_dt.Rows[0].Table.Columns.Contains("OtherAgentID"))
                    {
                        System.Text.StringBuilder _strReturnMessageBuilder = new System.Text.StringBuilder();
                        _strReturnMessageBuilder.Append("<table bgcolor='#ffffcc' width='450' cellpadding='5' cellspacing='5'>");
                        _strReturnMessageBuilder.Append("<tr><td colspan='3'><b style='color:red;'>" + Resources.General.FOUND + ":" + Resources.ResultPage.SmsgSorryFoundOtherAgentRecord + "</b></tr>");
                        _strReturnMessage += Resources.ResultPage.SmsgAgent + ": <b>" + _dt.Rows[0]["OtherAgentName"].ToString() + "</b>";
                        _strReturnMessageBuilder.Append("<tr><td>" + Resources.General.Broker + "</td><td>:</td><td><b>" + _dt.Rows[0]["OtherAgentName"].ToString() + "</b></td></tr>");
                        
                        _callType = Convert.ToInt16(_dt.Rows[0]["CallType"].ToString());
                        if (_callType == 100)
                        {
                           
                            _strReturnMessageBuilder.Append("<tr><td>" + Resources.General.CallType + "</td><td>:</td><td><b style='color:green;'>" + Resources.General.FirstFollowUpCall + "</b></td></tr>");
                        }
                        else if (_callType == 101)
                        {
                            _strReturnMessageBuilder.Append("<tr><td>" + Resources.General.CallType + "</td><td>:</td><td><b style='color:red;'>" + Resources.General.CallMeRequest + "</b></td></tr>");
                            _strReturnMessageBuilder.Append("<tr><td>" + Resources.ResultPage.SmsgTime + "</td><td>:</td><td><b>" + _dt.Rows[0]["CallTime"].ToString() + "</b></td></tr>");
                            _strReturnMessageBuilder.Append("<tr><td>" + Resources.CarInsurance.CompanyName + "</td><td>:</td><td><b>" + _dt.Rows[0]["ProviderCompanyName"].ToString() + "</b></td></tr>");
                            _strReturnMessageBuilder.Append("<tr><td>" + Resources.ResultPage.SmsgRequestOn + "</td><td>:</td><td><b>" + _dt.Rows[0]["CallMeRequestDateTime"].ToString() + "</b></td></tr>");

                        }

                       
                        _callStatus = Convert.ToInt16(_dt.Rows[0]["CallStatus"].ToString());
                        if (_callStatus == 1)
                        {
                            
                            _strReturnMessageBuilder.Append("<tr><td>" + Resources.General.Status + "</td><td>:</td><td><b style='color:green;'>" + Resources.General.Pending + "</b></td></tr>");
                        }
                        else if (_callStatus == 2)
                        {
                            
                            _strReturnMessageBuilder.Append("<tr><td>" + Resources.General.Status + "</td><td>:</td><td><b style='color:red;'>" + Resources.General.Callback + "</b></td></tr>");
                        }
                        else if (_callStatus == 3)
                        {
                            
                            _strReturnMessageBuilder.Append("<tr><td>" + Resources.General.Status + "</td><td>:</td><td><b style='color:blue;'>" + Resources.General.FollowUp + "</b></td></tr>");
                        }

                        if (_dt.Rows[0]["OtherAgentCallBackDateTime"] != DBNull.Value)
                        {
                            _strReturnMessageBuilder.Append("<tr><td>" + Resources.General.Callback + " " + Resources.General.DateTime + "</td><td>:</td><td><b>" + Convert.ToDateTime(_dt.Rows[0]["OtherAgentCallBackDateTime"].ToString()).ToString("dd/MMM/yyyy hh:mm tt") + "</b></td></tr>");
                        }
                        if (_dt.Rows[0]["ModifiedDateTime"] != DBNull.Value)
                        {
                            _strReturnMessageBuilder.Append("<tr><td>" + Resources.General.DateTime + "</td><td>:</td><td><b>" + Convert.ToDateTime(_dt.Rows[0]["ModifiedDateTime"].ToString()).ToString("dd/MMM/yyyy hh:mm tt") + "</b></td></tr>");
                        }

                        _strReturnMessageBuilder.Append("<tr><td>" + Resources.ResultPage.SmsgTakeOver + "</td><td>:</td><td><a onclick='javascript:return confirm(\"" + Resources.ResultPage.SmsgAreUsureCallNow + "\");' href='ViewCINoMatchFound.aspx?" + "leadid=" + _dt.Rows[0]["OtherAgentLeadID"].ToString() + "&carid=" + txtCarId.Text + "&custid=" + _dt.Rows[0]["OtherAgentCustomerID"].ToString() + "&calltype=" + _dt.Rows[0]["CallType"].ToString() + "&otheragentid=" + _dt.Rows[0]["OtherAgentID"].ToString() + tabs + "'><b>[" + Resources.ResultPage.SmsgCallNow + "]</b></a></td>");
                        _strReturnMessageBuilder.Append("</table>");

                        lblNewCallMessage.Text = _strReturnMessageBuilder.ToString();
                    }
                    else if (_dt.Rows[0].Table.Columns.Contains("AgentLeadID"))
                    {
                        _callStatus = 1;
                        if (_dt.Rows[0].Table.Columns.Contains("CallStatus"))
                        {
                            if (_dt.Rows[0]["CallStatus"] != DBNull.Value)
                            {
                                _callStatus = Convert.ToInt16(_dt.Rows[0]["CallStatus"].ToString());
                            }
                        }

                        _callType = Convert.ToInt16(_dt.Rows[0]["CallType"].ToString());

                        if (_callStatus == 100)
                        {
                            _strReturnMessage += "<br/><b style='color:red;'>" + Resources.ResultPage.SmsgThisCarCloased + "</b>";
                            _strReturnMessage += "&nbsp;<a onclick='javascript:return confirm(\"" + Resources.ResultPage.SmsgAreUsureCallAgain + "\");' href='ViewCINoMatchFound.aspx?" + "leadid=" + _dt.Rows[0]["AgentLeadID"].ToString() + "&carid=" + txtCarId.Text + "&custid=" + _dt.Rows[0]["CustomerID"].ToString() + "&calltype=" + _dt.Rows[0]["CallType"].ToString() + tabs + "'><b>[" + Resources.ResultPage.SmsgCallAgainNow + "]</b></a>";
                            lblNewCallMessage.Text = _strReturnMessage;
                        }
                        else
                        {
                            if (_callType == 101)
                            {
                                _strReturnMessage += Resources.ResultPage.SmsgType + " : <b style='color:red;'>" + Resources.ResultPage.SmsgCallMe + "</b>";
                                _strReturnMessage += Resources.ResultPage.SmsgTime + " : <b>" + _dt.Rows[0]["CallTime"].ToString() + "</b>";
                                _strReturnMessage += Resources.ResultPage.SmsgCompany + " : <b>" + _dt.Rows[0]["ProviderCompanyName"].ToString() + "</b>";
                                _strReturnMessage += Resources.ResultPage.SmsgRequestOn + " : <b>" + Convert.ToDateTime(_dt.Rows[0]["CallMeRequestDateTime"].ToString()).ToString("dd/MMM/yyyy hh:mm tt") + "</b>";
                                _strReturnMessage += "&nbsp;<a onclick='javascript:return confirm(\"" + Resources.ResultPage.SmsgAreUsureCallNow + "\");' href='ViewCINoMatchFound.aspx?" + "leadid=" + _dt.Rows[0]["AgentLeadID"].ToString() + "&carid=" + txtCarId.Text + "&custid=" + _dt.Rows[0]["CustomerID"].ToString() + "&calltype=" + _dt.Rows[0]["CallType"].ToString() + tabs + "'><b>[" + Resources.ResultPage.SmsgCallNow + "]</b></a>";
                                lblNewCallMessage.Text = _strReturnMessage;
                            }
                            else if (_callType == 102)
                            {
                                _strReturnMessage += Resources.ResultPage.SmsgType + " : <b style='color:red;'>CALL ME BACK</b>";
                                _strReturnMessage += Resources.ResultPage.SmsgTime + " : <b>" + _dt.Rows[0]["CallTime"].ToString() + "</b>";
                                _strReturnMessage += Resources.ResultPage.SmsgCompany + " : <b>" + _dt.Rows[0]["ProviderCompanyName"].ToString() + "</b>";
                                _strReturnMessage += Resources.ResultPage.SmsgRequestOn + " : <b>" + Convert.ToDateTime(_dt.Rows[0]["CallMeRequestDateTime"].ToString()).ToString("dd/MMM/yyyy hh:mm tt") + "</b>";
                                _strReturnMessage += "&nbsp;<a onclick='javascript:return confirm(\"" + Resources.ResultPage.SmsgAreUsureCallNow + "\");' href='ViewCINoMatchFound.aspx?" + "leadid=" + _dt.Rows[0]["AgentLeadID"].ToString() + "&carid=" + txtCarId.Text + "&custid=" + _dt.Rows[0]["CustomerID"].ToString() + "&callmeid=" + _dt.Rows[0]["CallMeID"].ToString() + "&calltype=" + _dt.Rows[0]["CallType"].ToString() + tabs + "'><b>[" + Resources.ResultPage.SmsgCallNow + "]</b></a>";
                                lblNewCallMessage.Text = _strReturnMessage;
                            }
                            else
                            {
                                _strReturnMessage = "leadid=" + _dt.Rows[0]["AgentLeadID"].ToString() + "&carid=" + txtCarId.Text + "&custid=" + _dt.Rows[0]["CustomerID"].ToString() + "&calltype=" + _dt.Rows[0]["CallType"].ToString() + tabs;
                                Response.Redirect("ViewCINoMatchFound.aspx?" + _strReturnMessage);
                            }
                        }
                    }
                }
            }
        }
        catch (Exception Ex)
        {
            
        }
    }

    #endregion

    #region Not Using - 10 Jul 2012

  
    //public string GenerateNonGGExcel(Int64 CECarId, Int64 ProviderId, string Language)
    //{
    //    DataSet _dsApplication = new DataSet();
    //    NonGGPackageDB _nonggpackagedb = new NonGGPackageDB();
    //    _dsApplication = _nonggpackagedb.GetNonGGApplication(CECarId, ProviderId, 1);
    //    string _html = "";
    //    if (_dsApplication.Tables[0].Rows.Count > 0)
    //    {

    //        #region Variable Declaration

    //        string Title, Name, DOB, Gender, Occupation, ContactNo, Email, PresentAddress, SubDistrict, District, Province, PostalCode, Insurer, Package, NoOfDriver;
    //        string InsuranceType, GarageType, CarModelYear, CarMakeModel, Size, VehicleWeight, NumberofSeat, Beneficiary, VehicleType, SumInsured, NCB;
    //        string CurrentInsurer, CarPlate, CarPlateProvince, EngineNumber, ChassisNumber, Modification, AnyClaims, AddDrivers, CommencementDate;
    //        string Premium, CTPL, CTPLAmount, TotalPremium, PaymentType, QuoteRefNo, Payment, ApplicationDate;

    //        Title = ""; Name = ""; DOB = ""; Gender = ""; Occupation = ""; ContactNo = ""; Email = ""; PresentAddress = ""; SubDistrict = ""; District = "";
    //        Province = ""; PostalCode = ""; Insurer = ""; Package = ""; NoOfDriver = ""; InsuranceType = ""; GarageType = ""; CarModelYear = "";
    //        CarMakeModel = ""; Size = ""; VehicleWeight = ""; NumberofSeat = ""; Beneficiary = ""; VehicleType = ""; SumInsured = ""; NCB = "";
    //        CurrentInsurer = ""; CarPlate = ""; CarPlateProvince = ""; EngineNumber = ""; ChassisNumber = ""; Modification = ""; AnyClaims = "";
    //        AddDrivers = ""; CommencementDate = ""; Premium = ""; CTPL = ""; CTPLAmount = ""; TotalPremium = ""; PaymentType = "";
    //        QuoteRefNo = ""; Payment = ""; ApplicationDate = "";
    //        //For Driver
    //        string DriverName1, DriverDOB1, DriverName2, DriverDOB2, Driver1LicenseNo, Driver2LicenseNo, Driver1IDNo, Driver2IDNo;
    //        DriverName1 = ""; DriverDOB1 = ""; DriverName2 = ""; DriverDOB2 = ""; Driver1LicenseNo = ""; Driver2LicenseNo = "";
    //        Driver1IDNo = ""; Driver2IDNo = "";

    //        #endregion

    //        #region Assign Values

    //        Email = _dsApplication.Tables[0].Rows[0]["Email"].ToString();
    //        Title = _dsApplication.Tables[0].Rows[0]["Title"].ToString();
    //        Name = _dsApplication.Tables[0].Rows[0]["Name"].ToString();
    //        DOB = _dsApplication.Tables[0].Rows[0]["DOB"].ToString();
    //        Gender = _dsApplication.Tables[0].Rows[0]["Gender"].ToString();
    //        Occupation = _dsApplication.Tables[0].Rows[0]["Occupation"].ToString();
    //        ContactNo = _dsApplication.Tables[0].Rows[0]["ContactNo"].ToString();
    //        Beneficiary = _dsApplication.Tables[0].Rows[0]["Beneficiary"].ToString();
    //        PresentAddress = _dsApplication.Tables[0].Rows[0]["PresentAddress"].ToString();
    //        SubDistrict = _dsApplication.Tables[0].Rows[0]["SubDistrict"].ToString();
    //        District = _dsApplication.Tables[0].Rows[0]["District"].ToString();
    //        Province = _dsApplication.Tables[0].Rows[0]["Province"].ToString();
    //        PostalCode = _dsApplication.Tables[0].Rows[0]["PostalCode"].ToString();
    //        Insurer = _dsApplication.Tables[0].Rows[0]["CompanyName"].ToString();
    //        Package = _dsApplication.Tables[0].Rows[0]["Package"].ToString();
    //        NoOfDriver = _dsApplication.Tables[0].Rows[0]["NoOfDriver"].ToString();
    //        if (NoOfDriver.ToString() == "0")
    //        {
    //            AddDrivers = "No";
    //        }
    //        else
    //        {
    //            AddDrivers = "Yes";
    //        }
    //        InsuranceType = _dsApplication.Tables[0].Rows[0]["InsuranceType"].ToString();
    //        GarageType = _dsApplication.Tables[0].Rows[0]["GarageType"].ToString();
    //        CarModelYear = _dsApplication.Tables[0].Rows[0]["CarModelYear"].ToString();
    //        CarMakeModel = _dsApplication.Tables[0].Rows[0]["CarMakeModel"].ToString();
    //        Size = _dsApplication.Tables[0].Rows[0]["Size"].ToString();
    //        VehicleWeight = _dsApplication.Tables[0].Rows[0]["VehicleWeight"].ToString();
    //        NumberofSeat = _dsApplication.Tables[0].Rows[0]["NumberofSeat"].ToString();
    //        EngineNumber = _dsApplication.Tables[0].Rows[0]["EngineNumber"].ToString();
    //        ChassisNumber = _dsApplication.Tables[0].Rows[0]["ChassisNumber"].ToString();
    //        Beneficiary = _dsApplication.Tables[0].Rows[0]["Beneficiary"].ToString();
    //        VehicleType = _dsApplication.Tables[0].Rows[0]["VehicleType"].ToString();
    //        SumInsured = _dsApplication.Tables[0].Rows[0]["SumInsured"].ToString();
    //        NCB = _dsApplication.Tables[0].Rows[0]["NCB"].ToString();
    //        CurrentInsurer = _dsApplication.Tables[0].Rows[0]["CurrentInsurer"].ToString();
    //        CarPlate = _dsApplication.Tables[0].Rows[0]["CarPlate"].ToString();
    //        CarPlateProvince = _dsApplication.Tables[0].Rows[0]["ProvinceRegistration"].ToString();
    //        Modification = _dsApplication.Tables[0].Rows[0]["Accessories"].ToString();
    //        AnyClaims = _dsApplication.Tables[0].Rows[0]["AnyClaims"].ToString();
    //        CommencementDate = _dsApplication.Tables[0].Rows[0]["CommencementDate"].ToString();
    //        Premium = _dsApplication.Tables[0].Rows[0]["Premium"].ToString();

    //        CTPL = _dsApplication.Tables[0].Rows[0]["CTPL"].ToString();
    //        CTPLAmount = _dsApplication.Tables[0].Rows[0]["CTPLAmount"].ToString();
    //        TotalPremium = _dsApplication.Tables[0].Rows[0]["TotalPremium"].ToString();
    //        PaymentType = _dsApplication.Tables[0].Rows[0]["PaymentType"].ToString();
    //        QuoteRefNo = _dsApplication.Tables[0].Rows[0]["QuoteRefNo"].ToString();
    //        Payment = _dsApplication.Tables[0].Rows[0]["Payment"].ToString();
    //        ApplicationDate = _dsApplication.Tables[0].Rows[0]["OrderDate"].ToString();

    //        if (AddDrivers == "Yes")
    //        {
    //            if (_dsApplication.Tables[1].Rows.Count > 0)
    //            {
    //                if (Convert.ToInt16(NoOfDriver) > 0)
    //                {
    //                    DriverName1 = _dsApplication.Tables[1].Rows[0]["FullName"].ToString();
    //                    DriverDOB1 = _dsApplication.Tables[1].Rows[0]["DOB"].ToString();
    //                    Driver1IDNo = _dsApplication.Tables[1].Rows[0]["IDNo"].ToString();
    //                    Driver1LicenseNo = _dsApplication.Tables[1].Rows[0]["DrivingLicenseNumber"].ToString();
    //                }
    //                if (Convert.ToInt16(NoOfDriver) > 1)
    //                {

    //                    DriverName2 = _dsApplication.Tables[1].Rows[1]["FullName"].ToString();
    //                    DriverDOB2 = _dsApplication.Tables[1].Rows[1]["DOB"].ToString();
    //                    Driver2IDNo = _dsApplication.Tables[1].Rows[1]["IDNo"].ToString();
    //                    Driver2LicenseNo = _dsApplication.Tables[1].Rows[1]["DrivingLicenseNumber"].ToString();
    //                }
    //            }
    //        }

    //        #endregion

    //        #region Generate Excel File
    //        if (Language == "EN")
    //        {
    //            _html += "<html><body><table width='60%' cellpadding='1' cellspacing='1' border='1'>";
    //            _html += "<tr><td align='left' colspan='2'><b>Applicant Details</b></td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>Prefix</b></td><td align='left'>" + Title + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>Applicant Name</b></td><td align='left'>" + Name + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>DOB</b></td><td style='mso-number-format:dd\\-mmm\\-yyyy' align='left'>" + DOB + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>Gender</b></td><td align='left'>" + Gender + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>Occupation</b></td><td align='left'>" + Occupation + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>ContactNo</b></td><td style='mso-number-format:\\@' align='left'>" + ContactNo + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>PresentAddress</b></td><td align='left'>" + PresentAddress + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>SubDistrict</b></td><td align='left'>" + SubDistrict + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>District</b></td><td align='left'>" + District + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>Province</b></td><td align='left'>" + Province + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>PostalCode</b></td><td align='left'>" + PostalCode + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>Insurer</b></td><td align='left'>" + Insurer + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>Package</b></td><td align='left'>" + Package + "</td></tr>";

    //            _html += "<tr><td width='300' align='left'><b>Specify Named Driver</b></td><td align='left'>" + AddDrivers + "</td></tr>";
    //            if (AddDrivers == "Yes")
    //            {
    //                _html += "<tr><td width='300' align='left'><b>Number Of Named Driver</b></td><td align='left'>" + NoOfDriver + "</td></tr>";
    //            }
    //            if (Convert.ToInt16(NoOfDriver) > 0)
    //            {
    //                _html += "<tr><td width='300' align='left'><b>DOB of 1st Driver</b></td><td style='mso-number-format:dd\\-mmm\\-yyyy' align='left'>" + DriverDOB1 + "</td></tr>";
    //                _html += "<tr><td width='300' align='left'><b>Name of 1st Driver</b></td><td align='left'>" + DriverName1 + "</td></tr>";
    //                _html += "<tr><td width='300' align='left'><b>First Driver's ID No.</b></td><td style='mso-number-format:\\@' align='left'>" + Driver1IDNo + "</td></tr>";
    //                _html += "<tr><td width='300' align='left'><b>First Driver's License No.</b></td><td  align='left'>" + Driver1LicenseNo + "</td></tr>";
    //            }
    //            if (Convert.ToInt16(NoOfDriver) > 1)
    //            {
    //                _html += "<tr><td width='300' align='left'><b>DOB of 2nd Driver</b></td><td style='mso-number-format:dd\\-mmm\\-yyyy' align='left'>" + DriverDOB2 + "</td></tr>";
    //                _html += "<tr><td width='300' align='left'><b>Nameof 2nd Driver</b></td><td align='left'>" + DriverName2 + "</td></tr>";
    //                _html += "<tr><td width='300' align='left'><b>Second Driver's ID No.</b></td><td style='mso-number-format:\\@' align='left'>" + Driver2IDNo + "</td></tr>";
    //                _html += "<tr><td width='300' align='left'><b>Second Driver's License No.</b></td><td  align='left'>" + Driver2LicenseNo + "</td></tr>";
    //            }

    //            _html += "<tr><td width='300' align='left'><b>InsuranceType</b></td><td align='left'>" + InsuranceType + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>GarageType</b></td><td align='left'>" + GarageType + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>CarModelYear</b></td><td align='left'>" + CarModelYear + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>CarMakeModel</b></td><td align='left'>" + CarMakeModel + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>Size (cc.)</b></td><td align='left'>" + Size + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>Gross Vehicle Weight (kgs)</b></td><td align='left'>" + VehicleWeight + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>Number of seat</b></td><td align='left'>" + NumberofSeat + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>Beneficiary</b></td><td align='left'>" + Beneficiary + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>VehicleType</b></td><td align='left'>" + VehicleType + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>SumInsured</b></td><td style='mso-number-format:\\#\\,\\#\\#0\\.00' align='left'>" + SumInsured + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>NCB</b></td><td align='left'>" + NCB + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>CurrentInsurer</b></td><td align='left'>" + CurrentInsurer + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>Car Plate</b></td><td align='left'>" + CarPlate + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>Car Plate Province</b></td><td align='left'>" + CarPlateProvince + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>EngineNumber</b></td><td align='left'>" + EngineNumber + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>ChassisNumber</b></td><td align='left'>" + ChassisNumber + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>Added Accessories Or Modifications?</b></td><td align='left'>" + Modification + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>Any Claim in Last Year?</b></td><td align='left'>" + AnyClaims + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>The insurance coverage Starts</b></td><td align='left'style='mso-number-format:dd\\-MM\\-yyyy'>" + CommencementDate + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>Voluntary Insurance Premium</b></td><td style='mso-number-format:\\#\\,\\#\\#0\\.00' align='left'>" + Premium + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>CTPL</b></td><td align='left'>" + CTPL + "</td></tr>";
    //            if (CTPL == "Yes")
    //            {
    //                _html += "<tr><td width='300' align='left'><b>CTPL Amount</b></td><td style='mso-number-format:\\#\\,\\#\\#0\\.00' align='left'>" + CTPLAmount + "</td></tr>";
    //            }
    //            _html += "<tr><td width='300' align='left'><b>Total Premium</b></td><td style='mso-number-format:\\#\\,\\#\\#0\\.00' align='left'>" + TotalPremium + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>ApplicationDate</b></td><td style='mso-number-format:dd\\-mmm\\-yyyy\\ hh\\:mm\\ AM\\/PM' align='left'>" + ApplicationDate + "</td></tr>";

    //            _html += "</table></body></html>";
    //        }
    //        else if (Language == "TH")
    //        {
    //            _html += "<html><body><table width='60%' cellpadding='1' cellspacing='1' border='1'>";
    //            _html += "<tr><td align='left' colspan='2'><b>รายละเอียดผู้ทำประกัน</b></td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>คำนำหน้า</b></td><td  align='left'>" + Title + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>ชื่อผู้ทำประกัน</b></td><td  align='left'>" + Name + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>วันเกิด</b></td><td style='mso-number-format:dd\\-mmm\\-yyyy'  align='left'>" + DOB + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>เพศ</b></td><td  align='left'>" + Gender + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>อาชีพ</b></td><td  align='left'>" + Occupation + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>เบอร์ติดต่อ</b></td><td style='mso-number-format:\\@' align='left'>" + ContactNo + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>ที่อยู่ปัจจุบัน</b></td><td  align='left'>" + PresentAddress + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>แขวง/ตำบล</b></td><td  align='left'>" + SubDistrict + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>เขต/อำเภอ</b></td><td  align='left'>" + District + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>จังหวัด</b></td><td  align='left'>" + Province + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>รหัสไปรษณีย์</b></td><td  align='left'>" + PostalCode + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>บริษัทประกัน</b></td><td  align='left'>" + Insurer + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>แพกเก็จ</b></td><td  align='left'>" + Package + "</td></tr>";

    //            _html += "<tr><td width='300' align='left'><b>ระบุผู้ขับขี่</b></td><td  align='left'>" + AddDrivers + "</td></tr>";
    //            if (AddDrivers == "Yes")
    //            {
    //                _html += "<tr><td width='300' align='left'><b>จำนวนผู้ขับขี่</b></td><td  align='left'>" + NoOfDriver + "</td></tr>";
    //            }
    //            if (Convert.ToInt16(NoOfDriver) > 0)
    //            {
    //                _html += "<tr><td width='300' align='left'><b>วันเกิด ผู้ขับขี่คนที่ 1</b></td><td  style='mso-number-format:dd\\-mmm\\-yyyy' align='left'>" + DriverDOB1 + "</td></tr>";
    //                _html += "<tr><td width='300' align='left'><b>ผู้ขับขี่คนที่ 1</b></td><td  align='left'>" + DriverName1 + "</td></tr>";
    //                _html += "<tr><td width='300' align='left'><b>ผู้ขับขี่คนที่ 1 เลขที่บัตรประชาชน</b></td><td style='mso-number-format:\\@' align='left'>" + Driver1IDNo + "</td></tr>";
    //                _html += "<tr><td width='300' align='left'><b>ผู้ขับขี่คนที่ 1 เลขที่ใบขับขี่</b></td><td  align='left'>" + Driver1LicenseNo + "</td></tr>";
    //            }
    //            if (Convert.ToInt16(NoOfDriver) > 1)
    //            {
    //                _html += "<tr><td width='300' align='left'><b>วันเกิด ผู้ขับขี่คนที่ 2</b></td><td  style='mso-number-format:dd\\-mmm\\-yyyy' align='left'>" + DriverDOB2 + "</td></tr>";
    //                _html += "<tr><td width='300' align='left'><b>ผู้ขับขี่คนที่ 2</b></td><td  align='left'>" + DriverName2 + "</td></tr>";
    //                _html += "<tr><td width='300' align='left'><b>ผู้ขับขี่คนที่ 2 เลขที่บัตรประชาชน</b></td><td style='mso-number-format:\\@' align='left'>" + Driver2IDNo + "</td></tr>";
    //                _html += "<tr><td width='300' align='left'><b>ผู้ขับขี่คนที่ 2 เลขที่ใบขับขี่</b></td><td  align='left'>" + Driver2LicenseNo + "</td></tr>";
    //            }
    //            _html += "<tr><td width='300' align='left'><b>ประเภทประกัน</b></td><td  align='left'>" + InsuranceType + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>ประเภทอู่</b></td><td  align='left'>" + GarageType + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>ปีของรถ</b></td><td  align='left'>" + CarModelYear + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>รุ่น</b></td><td  align='left'>" + CarMakeModel + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>ขนาด (cc.)</b></td><td  align='left'>" + Size + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>น้ำหนักรถ (kgs)</b></td><td align='left'>" + VehicleWeight + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>จำนวนที่นั่ง</b></td><td  align='left'>" + NumberofSeat + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>ผู้รับผลประโยชน์</b></td><td  align='left'>" + Beneficiary + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>ประเภทรถ</b></td><td  align='left'>" + VehicleType + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>ทุนประกัน</b></td><td style='mso-number-format:\\#\\,\\#\\#0\\.00'  align='left'>" + SumInsured + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>ส่วนลด NCB</b></td><td  align='left'>" + NCB + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>บริษัทประกันปัจจุบัน</b></td><td  align='left'>" + CurrentInsurer + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>ทะเบียนรถ</b></td><td  align='left'>" + CarPlate + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>จังหวัดที่จดทะเบียน</b></td><td  align='left'>" + CarPlateProvince + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>หมายเลขเครื่อง</b></td><td  align='left'>" + EngineNumber + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>หมายเลข Chassis</b></td><td  align='left'>" + ChassisNumber + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>มีอุปกรณ์พิเศษ?</b></td><td  align='left'>" + Modification + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>มีการเคลมปีที่แล้วหรือไม่?</b></td><td>" + AnyClaims + "</td></tr>";
    //            _html += "<tr><td width='300'  align='left'><b>วันที่เริ่มทำประกัน</b></td><td style='mso-number-format:dd\\-mmm\\-yyyy'  align='left'>" + CommencementDate + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>เบี้ยประกันภาคสมัครใจ</b></td><td style='mso-number-format:\\#\\,\\#\\#0\\.00' align='left'>" + Premium + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>พ.ร.บ.</b></td><td  align='left'>" + CTPL + "</td></tr>";
    //            if (CTPL == "Yes")
    //            {
    //                _html += "<tr><td width='300' align='left'><b>จำนวน (พ.ร.บ.)</b></td><td style='mso-number-format:\\#\\,\\#\\#0\\.00'  align='left'>" + CTPLAmount + "</td></tr>";
    //            }
    //            _html += "<tr><td width='300' align='left'><b>ราคารวม</b></td><td style='mso-number-format:\\#\\,\\#\\#0\\.00'  align='left'>" + TotalPremium + "</td></tr>";
    //            _html += "<tr><td width='300' align='left'><b>วันที่ทำรายการ</b></td><td style='mso-number-format:dd\\-mmm\\-yyyy\\ hh\\:mm\\ AM\\/PM'  align='left'>" + ApplicationDate + "</td></tr>";

    //            _html += "</table></body></html>";
    //        }
    //        #endregion
    //    }
    //    return _html;
    //}

    public string GenerateNonGGExcelInternal(Int64 CECarId, Int64 ProviderId, string FilePath, string FileName)
    {
        string _returnFilePath = "";
        Label lblContent = new Label();
        StringBuilder strText = new StringBuilder("");
        strText.Append("<table><tr><td colspan='2'><h3>ประกันภัยรถยนต์ - แบบฟอร์ม</h3></td></tr></table>");
        DataSet _dsApplication = new DataSet();
        NonGGPackageDB _nonggpackagedb = new NonGGPackageDB();
        _dsApplication = _nonggpackagedb.GetNonGGApplication(CECarId, ProviderId, 0);
        string _html = "";
        if (_dsApplication.Tables[0].Rows.Count > 0)
        {

            #region Variable Declaration

            string Title, Name, DOB, Gender, Occupation, ContactNo, Email, PresentAddress, SubDistrict, District, Province, PostalCode, Insurer, Package, NoOfDriver;
            string InsuranceType, GarageType, CarModelYear, CarMakeModel, Size, VehicleWeight, NumberofSeat, Beneficiary, VehicleType, SumInsured, NCB;
            string CurrentInsurer, CarPlate, CarPlateProvince, EngineNumber, ChassisNumber, Modification, AnyClaims, AddDrivers, CommencementDate;
            string Premium, CTPL, CTPLAmount, TotalPremium, PaymentType, QuoteRefNo, Payment, ApplicationDate;

            Title = ""; Name = ""; DOB = ""; Gender = ""; Occupation = ""; ContactNo = ""; Email = ""; PresentAddress = ""; SubDistrict = ""; District = "";
            Province = ""; PostalCode = ""; Insurer = ""; Package = ""; NoOfDriver = ""; InsuranceType = ""; GarageType = ""; CarModelYear = "";
            CarMakeModel = ""; Size = ""; VehicleWeight = ""; NumberofSeat = ""; Beneficiary = ""; VehicleType = ""; SumInsured = ""; NCB = "";
            CurrentInsurer = ""; CarPlate = ""; CarPlateProvince = ""; EngineNumber = ""; ChassisNumber = ""; Modification = ""; AnyClaims = "";
            AddDrivers = ""; CommencementDate = ""; Premium = ""; CTPL = ""; CTPLAmount = ""; TotalPremium = ""; PaymentType = "";
            QuoteRefNo = ""; Payment = ""; ApplicationDate = "";
            //For Driver
            string DriverName1, DriverDOB1, DriverName2, DriverDOB2, Driver1LicenseNo, Driver2LicenseNo, Driver1IDNo, Driver2IDNo;
            DriverName1 = ""; DriverDOB1 = ""; DriverName2 = ""; DriverDOB2 = ""; Driver1LicenseNo = ""; Driver2LicenseNo = "";
            Driver1IDNo = ""; Driver2IDNo = "";

            #endregion

            #region Assign Values

            Email = _dsApplication.Tables[0].Rows[0]["Email"].ToString();
            Title = _dsApplication.Tables[0].Rows[0]["Title"].ToString();
            Name = _dsApplication.Tables[0].Rows[0]["Name"].ToString();
            DOB = _dsApplication.Tables[0].Rows[0]["DOB"].ToString();
            Gender = _dsApplication.Tables[0].Rows[0]["Gender"].ToString();
            Occupation = _dsApplication.Tables[0].Rows[0]["Occupation"].ToString();
            ContactNo = _dsApplication.Tables[0].Rows[0]["ContactNo"].ToString();
            Beneficiary = _dsApplication.Tables[0].Rows[0]["Beneficiary"].ToString();
            PresentAddress = _dsApplication.Tables[0].Rows[0]["PresentAddress"].ToString();
            SubDistrict = _dsApplication.Tables[0].Rows[0]["SubDistrict"].ToString();
            District = _dsApplication.Tables[0].Rows[0]["District"].ToString();
            Province = _dsApplication.Tables[0].Rows[0]["Province"].ToString();
            PostalCode = _dsApplication.Tables[0].Rows[0]["PostalCode"].ToString();
            Insurer = _dsApplication.Tables[0].Rows[0]["CompanyName"].ToString();
            Package = _dsApplication.Tables[0].Rows[0]["Package"].ToString();
            NoOfDriver = _dsApplication.Tables[0].Rows[0]["NoOfDriver"].ToString();
            if (NoOfDriver.ToString() == "0")
            {
                AddDrivers = "No";
            }
            else
            {
                AddDrivers = "Yes";
            }
            InsuranceType = _dsApplication.Tables[0].Rows[0]["InsuranceType"].ToString();
            GarageType = _dsApplication.Tables[0].Rows[0]["GarageType"].ToString();
            CarModelYear = _dsApplication.Tables[0].Rows[0]["CarModelYear"].ToString();
            CarMakeModel = _dsApplication.Tables[0].Rows[0]["CarMakeModel"].ToString();
            Size = _dsApplication.Tables[0].Rows[0]["Size"].ToString();
            VehicleWeight = _dsApplication.Tables[0].Rows[0]["VehicleWeight"].ToString();
            NumberofSeat = _dsApplication.Tables[0].Rows[0]["NumberofSeat"].ToString();
            EngineNumber = _dsApplication.Tables[0].Rows[0]["EngineNumber"].ToString();
            ChassisNumber = _dsApplication.Tables[0].Rows[0]["ChassisNumber"].ToString();
            Beneficiary = _dsApplication.Tables[0].Rows[0]["Beneficiary"].ToString();
            VehicleType = _dsApplication.Tables[0].Rows[0]["VehicleType"].ToString();
            SumInsured = _dsApplication.Tables[0].Rows[0]["SumInsured"].ToString();
            NCB = _dsApplication.Tables[0].Rows[0]["NCB"].ToString();
            CurrentInsurer = _dsApplication.Tables[0].Rows[0]["CurrentInsurer"].ToString();
            CarPlate = _dsApplication.Tables[0].Rows[0]["CarPlate"].ToString();
            CarPlateProvince = _dsApplication.Tables[0].Rows[0]["ProvinceRegistration"].ToString();
            Modification = _dsApplication.Tables[0].Rows[0]["Accessories"].ToString();
            AnyClaims = _dsApplication.Tables[0].Rows[0]["AnyClaims"].ToString();
            CommencementDate = _dsApplication.Tables[0].Rows[0]["CommencementDate"].ToString();
            Premium = _dsApplication.Tables[0].Rows[0]["Premium"].ToString();

            CTPL = _dsApplication.Tables[0].Rows[0]["CTPL"].ToString();
            CTPLAmount = _dsApplication.Tables[0].Rows[0]["CTPLAmount"].ToString();
            TotalPremium = _dsApplication.Tables[0].Rows[0]["TotalPremium"].ToString();
            PaymentType = _dsApplication.Tables[0].Rows[0]["PaymentType"].ToString();
            QuoteRefNo = _dsApplication.Tables[0].Rows[0]["QuoteRefNo"].ToString();
            Payment = _dsApplication.Tables[0].Rows[0]["Payment"].ToString();
            ApplicationDate = _dsApplication.Tables[0].Rows[0]["OrderDate"].ToString();

            if (AddDrivers == "Yes")
            {
                if (_dsApplication.Tables[1].Rows.Count > 0)
                {
                    if (Convert.ToInt16(NoOfDriver) > 0)
                    {
                        DriverName1 = _dsApplication.Tables[1].Rows[0]["FullName"].ToString();
                        DriverDOB1 = _dsApplication.Tables[1].Rows[0]["DOB"].ToString();
                        Driver1IDNo = _dsApplication.Tables[1].Rows[0]["IDNo"].ToString();
                        Driver1LicenseNo = _dsApplication.Tables[1].Rows[0]["DrivingLicenseNumber"].ToString();
                    }
                    if (Convert.ToInt16(NoOfDriver) > 1)
                    {

                        DriverName2 = _dsApplication.Tables[1].Rows[1]["FullName"].ToString();
                        DriverDOB2 = _dsApplication.Tables[1].Rows[1]["DOB"].ToString();
                        Driver2IDNo = _dsApplication.Tables[1].Rows[1]["IDNo"].ToString();
                        Driver2LicenseNo = _dsApplication.Tables[1].Rows[1]["DrivingLicenseNumber"].ToString();
                    }
                }
            }

            #endregion

            #region Generate Excel File
            _html += "<html><body><table width='60%' cellpadding='1' cellspacing='1' border='1'>";
            _html += "<tr><td width='20%' align='left' colspan='2'><b>รายละเอียดผู้ทำประกัน</b></td></tr>";
            _html += "<tr><td width='300' align='left'><b>คำนำหน้า</b></td><td  align='left'>" + Title + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>ชื่อผู้ทำประกัน</b></td><td  align='left'>" + Name + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>วันเกิด</b></td><td style='mso-number-format:dd\\-mmm\\-yyyy'  align='left'>" + DOB + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>เพศ</b></td><td  align='left'>" + Gender + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>อาชีพ</b></td><td  align='left'>" + Occupation + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>เบอร์ติดต่อ</b></td><td style='mso-number-format:\\@' align='left'>" + ContactNo + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>ที่อยู่ปัจจุบัน</b></td><td  align='left'>" + PresentAddress + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>แขวง/ตำบล</b></td><td  align='left'>" + SubDistrict + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>เขต/อำเภอ</b></td><td  align='left'>" + District + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>จังหวัด</b></td><td  align='left'>" + Province + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>รหัสไปรษณีย์</b></td><td  align='left'>" + PostalCode + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>บริษัทประกัน</b></td><td  align='left'>" + Insurer + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>แพกเก็จ</b></td><td  align='left'>" + Package + "</td></tr>";

            _html += "<tr><td width='300' align='left'><b>ระบุผู้ขับขี่</b></td><td  align='left'>" + AddDrivers + "</td></tr>";
            if (AddDrivers == "Yes")
            {
                _html += "<tr><td width='300' align='left'><b>จำนวนผู้ขับขี่</b></td><td  align='left'>" + NoOfDriver + "</td></tr>";
            }
            if (Convert.ToInt16(NoOfDriver) > 0)
            {
                _html += "<tr><td width='300' align='left'><b>วันเกิด ผู้ขับขี่คนที่ 1</b></td><td  style='mso-number-format:dd\\-mmm\\-yyyy' align='left'>" + DriverDOB1 + "</td></tr>";
                _html += "<tr><td width='300' align='left'><b>ผู้ขับขี่คนที่ 1</b></td><td  align='left'>" + DriverName1 + "</td></tr>";
                _html += "<tr><td width='300' align='left'><b>ผู้ขับขี่คนที่ 1 เลขที่บัตรประชาชน</b></td><td style='mso-number-format:\\@' align='left'>" + Driver1IDNo + "</td></tr>";
                _html += "<tr><td width='300' align='left'><b>ผู้ขับขี่คนที่ 1 เลขที่ใบขับขี่</b></td><td  align='left'>" + Driver1LicenseNo + "</td></tr>";
            }
            if (Convert.ToInt16(NoOfDriver) > 1)
            {
                _html += "<tr><td width='300' align='left'><b>วันเกิด ผู้ขับขี่คนที่ 2</b></td><td  style='mso-number-format:dd\\-mmm\\-yyyy' align='left'>" + DriverDOB2 + "</td></tr>";
                _html += "<tr><td width='300' align='left'><b>ผู้ขับขี่คนที่ 2</b></td><td  align='left'>" + DriverName2 + "</td></tr>";
                _html += "<tr><td width='300' align='left'><b>ผู้ขับขี่คนที่ 2 เลขที่บัตรประชาชน</b></td><td style='mso-number-format:\\@' align='left'>" + Driver2IDNo + "</td></tr>";
                _html += "<tr><td width='300' align='left'><b>ผู้ขับขี่คนที่ 2 เลขที่ใบขับข</b></td><td  align='left'>" + Driver2LicenseNo + "</td></tr>";
            }
            _html += "<tr><td width='300' align='left'><b>ประเภทประกัน</b></td><td  align='left'>" + InsuranceType + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>ประเภทอู่</b></td><td  align='left'>" + GarageType + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>ปีของรถ</b></td><td  align='left'>" + CarModelYear + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>รุ่น</b></td><td  align='left'>" + CarMakeModel + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>ขนาด (cc.)</b></td><td  align='left'>" + Size + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>น้ำหนักรถ (kgs)</b></td><td align='left'>" + VehicleWeight + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>จำนวนที่นั่ง</b></td><td  align='left'>" + NumberofSeat + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>ผู้รับผลประโยชน์</b></td><td  align='left'>" + Beneficiary + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>ประเภทรถ</b></td><td  align='left'>" + VehicleType + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>ทุนประกัน</b></td><td style='mso-number-format:\\#\\,\\#\\#0\\.00'  align='left'>" + SumInsured + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>ส่วนลด NCB</b></td><td  align='left'>" + NCB + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>บริษัทประกันปัจจุบัน</b></td><td  align='left'>" + CurrentInsurer + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>ทะเบียนรถ</b></td><td  align='left'>" + CarPlate + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>จังหวัดที่จดทะเบียน</b></td><td  align='left'>" + CarPlateProvince + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>หมายเลขเครื่อง</b></td><td  align='left'>" + EngineNumber + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>หมายเลข Chassis</b></td><td  align='left'>" + ChassisNumber + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>มีอุปกรณ์พิเศษ?</b></td><td  align='left'>" + Modification + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>มีการเคลมปีที่แล้วหรือไม่?</b></td><td>" + AnyClaims + "</td></tr>";
            _html += "<tr><td width='300'  align='left'><b>วันที่เริ่มทำประกัน</b></td><td style='mso-number-format:dd\\-mmm\\-yyyy'  align='left'>" + CommencementDate + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>เบี้ยประกันภาคสมัครใจ</b></td><td style='mso-number-format:\\#\\,\\#\\#0\\.00' align='left'>" + Premium + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>พ.ร.บ.</b></td><td  align='left'>" + CTPL + "</td></tr>";
            if (CTPL == "Yes")
            {
                _html += "<tr><td width='300' align='left'><b>จำนวน (พ.ร.บ.)</b></td><td style='mso-number-format:\\#\\,\\#\\#0\\.00'  align='left'>" + CTPLAmount + "</td></tr>";
            }
            _html += "<tr><td width='300' align='left'><b>ราคารวม</b></td><td style='mso-number-format:\\#\\,\\#\\#0\\.00'  align='left'>" + TotalPremium + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>วันที่ทำรายการ</b></td><td style='mso-number-format:dd\\-mmm\\-yyyy\\ hh\\:mm\\ AM\\/PM'  align='left'>" + ApplicationDate + "</td></tr>";

            _html += "</table></body></html>";
            #endregion

            lblContent.Text = _html;
            MyIO myio = new MyIO();

            string[] filecontent = new string[1];
            filecontent[0] = lblContent.Text.ToString();

            myio.WriteNewFile(FilePath, FileName + ".xls", filecontent);
            _returnFilePath = FilePath + FileName + ".xls";
        }
        return _returnFilePath;
    }

    private string GetQuoteRefNoByProvider(Int64 _ProviderId, Int64 CarID)
    {
        string QuoteRefNo = "";
        string convertno = General.GetRefNumber(CarID);
        if (_ProviderId == 11)
        {
            QuoteRefNo = "AZC" + convertno.ToString();
        }
        else if (_ProviderId == 12)
        {
            QuoteRefNo = "MSI" + convertno.ToString();
        }
        else if (_ProviderId == 16)
        {
            QuoteRefNo = "AXA" + convertno.ToString();
        }
        else if (_ProviderId == 29)
        {
            QuoteRefNo = "LMG" + convertno.ToString();
        }
        else if (_ProviderId == 31)
        {
            QuoteRefNo = "CTS" + convertno.ToString();
        }
        else if (_ProviderId == 32)
        {
            QuoteRefNo = "BKI" + convertno.ToString();
        }
        else if (_ProviderId == 33)
        {
            QuoteRefNo = "MTI" + convertno.ToString();
        }
        else if (_ProviderId == 41)
        {
            QuoteRefNo = "KUR" + convertno.ToString();
        }
        else if (_ProviderId == 46)
        {
            QuoteRefNo = "TMS" + convertno.ToString();
        }
        else if (_ProviderId == 35)
        {
            QuoteRefNo = "KPI" + convertno.ToString();
        }
        return QuoteRefNo;
    }

    public string GetReferenceNumber(string Number, string ProviderId)
    {
        string convertno = CE.Global.General.GetRefNumber(Convert.ToInt64(Number.ToString()));
        string _RefNo = "";
        if (ProviderId == "11")
        {
            _RefNo = "AZC" + convertno.ToString();
        }
        else if (ProviderId == "12")
        {
            _RefNo = "MSI" + convertno.ToString();
        }
        else if (ProviderId == "16")
        {
            _RefNo = "AXA" + convertno.ToString();
        }
        else if (ProviderId == "29")
        {
            _RefNo = "LMG" + convertno.ToString();
        }
        else if (ProviderId == "31")
        {
            _RefNo = "CTS" + convertno.ToString();
        }
        else if (ProviderId == "32")
        {
            _RefNo = "BKI" + convertno.ToString();
        }
        else if (ProviderId == "33")
        {
            _RefNo = "MTI" + convertno.ToString();
        }
        else if (ProviderId == "41")
        {
            _RefNo = "KUR" + convertno.ToString();
        }
        else if (ProviderId == "46")
        {
            _RefNo = "TMS" + convertno.ToString();
        }
        else if (ProviderId == "35")
        {
            _RefNo = "KPI" + convertno.ToString();
        }
        return _RefNo;
    }

    private string GetProviderName(Int64 ProviderCompanyId)
    {
        string _result = "";
        if (ProviderCompanyId == 11)
        {
            _result = "อลิอันซ์ ซี.พี. ประกันภัย";
        }
        else if (ProviderCompanyId == 12)
        {
            _result = "เอ็ม เอส ไอ จี ประกันภัย";
        }
        else if (ProviderCompanyId == 16)
        {
            _result = "แอกซ่า ประกันภัย";
        }
        else if (ProviderCompanyId == 29)
        {
            _result = "แอลเอ็มจี ประกันภัย";
        }
        else if (ProviderCompanyId == 31)
        {
            _result = "นิวแฮมพ์เชอร์ อินชัวรันส์";
        }
        else if (ProviderCompanyId == 32)
        {
            _result = "กรุงเทพประกันภัย";
        }
        else if (ProviderCompanyId == 33)
        {
            _result = "เมืองไทยประกันภัย";
        }
        else if (ProviderCompanyId == 41)
        {
            _result = "เค เอส เค";// "คูเนีย ประกันภัย";
        }
        else if (ProviderCompanyId == 46)
        {
            _result = "โตเกียวมารีนศรีเมือง";
        }
        else if (ProviderCompanyId == 35)
        {
            _result = "กรุงไทยพานิชประกันภัย";
        }
        return _result;
    }

    private string GetProviderName(Int64 ProviderCompanyId, string Language)
    {
        string _result = "";
        if (Language == "1")
        {
            if (ProviderCompanyId == 11)
            {
                _result = "อลิอันซ์ ซี.พี. ประกันภัย";
            }
            else if (ProviderCompanyId == 12)
            {
                _result = "เอ็ม เอส ไอ จี ประกันภัย";
            }
            else if (ProviderCompanyId == 16)
            {
                _result = "แอกซ่า ประกันภัย";
            }
            else if (ProviderCompanyId == 29)
            {
                _result = "แอลเอ็มจี ประกันภัย";
            }
            else if (ProviderCompanyId == 31)
            {
                _result = "นิวแฮมพ์เชอร์ อินชัวรันส์";
            }
            else if (ProviderCompanyId == 32)
            {
                _result = "กรุงเทพประกันภัย";
            }
            else if (ProviderCompanyId == 33)
            {
                _result = "เมืองไทยประกันภัย";
            }
            else if (ProviderCompanyId == 41)
            {
                _result = "เค เอส เค";// _result = "คูเนีย ประกันภัย";
            }
            else if (ProviderCompanyId == 46)
            {
                _result = "โตเกียวมารีนศรีเมือง";
            }
            else if (ProviderCompanyId == 35)
            {
                _result = "กรุงไทยพานิชประกันภัย";
            }
        }
        else if (Language == "2")
        {
            if (ProviderCompanyId == 11)
            {
                _result = "Allianz CP Insurance";
            }
            else if (ProviderCompanyId == 12)
            {
                _result = "MSIG Insurance";
            }
            else if (ProviderCompanyId == 16)
            {
                _result = "AXA Insurance";
            }
            else if (ProviderCompanyId == 29)
            {
                _result = "LMG  Insurance";
            }
            else if (ProviderCompanyId == 31)
            {
                _result = "Chartis Insurance";
            }
            else if (ProviderCompanyId == 32)
            {
                _result = "BKI Insurance";
            }
            else if (ProviderCompanyId == 33)
            {
                _result = "MuangThai Insurance";
            }
            else if (ProviderCompanyId == 41)
            {
                _result = "KSK Insurance";
            }
            else if (ProviderCompanyId == 46)
            {
                _result = "Tokio Marine Insurance";
            }
            else if (ProviderCompanyId == 35)
            {
                _result = "KrungThai Insurance";
            }
        }
        return _result;
    }

    private string GetProviderBrokerCode(Int64 ProviderCompanyId)
    {
        string _result = "";
        if (ProviderCompanyId == 11)
        {
            _result = "001600";
        }
        else if (ProviderCompanyId == 12)
        {
            _result = "AFM1012";
        }
        else if (ProviderCompanyId == 16)
        {
            _result = "BB115";
        }
        else if (ProviderCompanyId == 29)
        {
            _result = "BR00619";
        }
        else if (ProviderCompanyId == 31)
        {
            _result = "002851000";
        }
        else if (ProviderCompanyId == 32)
        {
            _result = "641100";
        }
        else if (ProviderCompanyId == 33)
        {
            _result = "74000352";
        }
        else if (ProviderCompanyId == 41)
        {
            _result = "198700-00";
        }
        else if (ProviderCompanyId == 46)
        {
            _result = "10233002";
        }
        else if (ProviderCompanyId == 35)
        {
            _result = "-/207";
        }
        return _result;
    }

    private string GetProviderMail(Int64 ProviderCompanyId)
    {
        string _result = "";
        if (ProviderCompanyId == 11)
        {
            _result = "TO_AZCP";
        }
        else if (ProviderCompanyId == 12)
        {
            _result = "TO_MSIG";
        }
        else if (ProviderCompanyId == 16)
        {
            _result = "TO_AXA";
        }
        else if (ProviderCompanyId == 29)
        {
            _result = "TO_LMG";
        }
        else if (ProviderCompanyId == 31)
        {
            _result = "TO_CTS";
        }
        else if (ProviderCompanyId == 32)
        {
            _result = "TO_BKI";
        }
        else if (ProviderCompanyId == 33)
        {
            _result = "TO_MTI";
        }
        else if (ProviderCompanyId == 41)
        {
            _result = "TO_KUR";
        }
        else if (ProviderCompanyId == 46)
        {
            _result = "TO_TMS";
        }
        else if (ProviderCompanyId == 35)
        {
            _result = "TO_KPI";
        }
        return _result;
    }

    private string GetProvider(Int64 ProviderCompanyId)
    {
        string _result = "";
        if (ProviderCompanyId == 11)
        {
            _result = "azcp";
        }
        else if (ProviderCompanyId == 12)
        {
            _result = "msig";
        }
        else if (ProviderCompanyId == 16)
        {
            _result = "axa";
        }
        else if (ProviderCompanyId == 29)
        {
            _result = "lmg";
        }
        else if (ProviderCompanyId == 31)
        {
            _result = "cts";
        }
        else if (ProviderCompanyId == 32)
        {
            _result = "bki";
        }
        else if (ProviderCompanyId == 33)
        {
            _result = "mti";
        }
        else if (ProviderCompanyId == 41)
        {
            _result = "kur";
        }
        else if (ProviderCompanyId == 46)
        {
            _result = "tms";
        }
        else if (ProviderCompanyId == 35)
        {
            _result = "kpi";
        }
        return _result;
    }

    private string GetProviderId(string Provider)
    {
        string _result = "0";
        if (Provider.ToUpper() == "AZC")
        {
            _result = "11";
        }
        else if (Provider.ToUpper() == "MSI")
        {
            _result = "12";
        }
        else if (Provider.ToUpper() == "AXA")
        {
            _result = "16";
        }
        else if (Provider.ToUpper() == "LMG")
        {
            _result = "29";
        }
        else if (Provider.ToUpper() == "CTS")
        {
            _result = "31";
        }
        else if (Provider.ToUpper() == "BKI")
        {
            _result = "32";
        }
        else if (Provider.ToUpper() == "MTI")
        {
            _result = "33";
        }
        else if (Provider.ToUpper() == "KUR")
        {
            _result = "41";
        }
        else if (Provider.ToUpper() == "TMS")
        {
            _result = "46";
        }
        else if (Provider.ToUpper() == "KPI")
        {
            _result = "35";
        }
        return _result;
    }

    #endregion

}
